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 Scala

1 Answer

0 votes
object ConvertArrayAndInt {
  // Function to convert an array of digits to an integer
  def convertArrayOfDigitsToIntNumber(arr: Array[Int]): Int = {
    var n = 0
    for (digit <- arr) {
      n = n * 10 + digit
    }
    n
  }

  // Function to convert an integer to an array of digits
  def convertIntNumberToArrayOfDigits(arr: Array[Int], n: Int): Unit = {
    var num = n
    var i = arr.length - 1
    while (num > 0 && i >= 0) {
      arr(i) = num % 10 // Extract last digit
      num = num / 10    // Remove the last digit
      i -= 1
    }
  }

  def main(args: Array[String]): Unit = {
    val arr = Array(9, 4, 6, 9) // Initial array of digits
    
    // Convert the array to an integer
    var n = convertArrayOfDigitsToIntNumber(arr)
    
    // Increment the integer
    n += 1
    
    // Convert the incremented integer back to an array of digits
    convertIntNumberToArrayOfDigits(arr, n)
    
    // Print the results
    println(s"n = $n")
    println(arr.mkString("[", ", ", "]"))
  }
}


  
     
/*
run:
  
n = 9470
[9, 4, 7, 0]

*/

 



answered Apr 12, 2025 by avibootz
...