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,845 questions

51,766 answers

573 users

How to convert an array of digits to an integer add 1 and convert it back to an array of digits in Swift

1 Answer

0 votes
import Foundation

// Function to convert an array of digits to an integer
func convertArrayOfDigitsToInt(_ arr: [Int]) -> Int {
    var n = 0
    for digit in arr {
        n = n * 10 + digit
    }
    return n
}

// Function to convert an integer to an array of digits
func convertIntToArrayOfDigits(_ digits: inout [Int], _ n: Int) {
    var number = n
    var i = digits.count - 1
    while number > 0 && i >= 0 {
        digits[i] = number % 10 // Extract the last digit
        number /= 10            // Remove the last digit
        i -= 1
    }
}

// Initial array of digits
var arr = [9, 4, 6, 9]
    
// Convert the array of digits to an integer
var n = convertArrayOfDigitsToInt(arr)
    
// Increment the integer
n += 1
    
// Convert the incremented integer back to an array of digits
convertIntToArrayOfDigits(&arr, n)
    
// Print the results
print("n = \(n)")
print(arr)



/*
run:

n = 9470
[9, 4, 7, 0]

*/

 



answered Apr 12, 2025 by avibootz
...