Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to get the first x leftmost digits of an integer number in Swift

1 Answer

0 votes
import Foundation

func xLeftmostDigit(n: Int, x: Int) -> Int {
    let powerOfTen = Int(pow(10.0, Double(x)))
    var number = n
    while number > powerOfTen {
        number /= 10
    }
    return number
}

for _ in 1...5 {
    let n = Int.random(in: 1...100000)
    let x = Int.random(in: 1...5)
    print("\(x) leftmost digit of \(n) is \(xLeftmostDigit(n: n, x: x))")
}


 
/*
run:
 
4 leftmost digit of 39033 is 3903
5 leftmost digit of 70165 is 70165
5 leftmost digit of 96759 is 96759
3 leftmost digit of 27733 is 277
1 leftmost digit of 63608 is 6

*/

 



answered Dec 8, 2024 by avibootz
...