0

Loop

I dont think the while loop works I have no way to check my answer Is this correct the sum is supposed to equal 0 fun main(args: Array<String>) { var num = readLine()!!.toInt() while (num <= 426) { num += 1 num /= 10 num %= 10 num /= 10 } println(num) }

7th Jan 2022, 2:35 PM
Ion Kare
Ion Kare - avatar
4 Answers
+ 4
I put a little comment in the snippet. Hope it explains things a bit fun main(args: Array<String>) { var num: Int = readLine()!!.toInt() var sum: Int = 0 while ( num != 0 ) { sum += num % 10 // add last digit of <num> to <sum> num /= 10 // remove last digit of <num> by dividing <num> by 10 } println( sum ) }
7th Jan 2022, 2:50 PM
Ipang
+ 2
What is this code supposed to do?
7th Jan 2022, 2:39 PM
Ipang
+ 1
I see thanks
7th Jan 2022, 2:55 PM
Ion Kare
Ion Kare - avatar
0
Finding the sum of the digits of a number is a popular coding challenge. Given a number as input, calculate and output its digit sum. Sample Input: 426 Sample Output: 12 Hint: Use a while loop to iterate over the number. During each iteration add the last digit to the sum by dividing the number by 10 and taking the remainder (num % 10), then remove the last digit of the number by dividing it by 10 (num / 10).
7th Jan 2022, 2:40 PM
Ion Kare
Ion Kare - avatar