English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to reverse a number using a while loop in Kotlin.
fun main(args: Array<String>) { var num = 1234 var reversed = 0 while (num != 0) { val digit = num % 10 reversed = reversed * 10 + digit num /= 10 } println("Reversed number: $reversed") }
When running this program, the output is:
Reversed number: 4321
In this program, the while loop is used to reverse the number by the following steps:
First, divide num by10The remainder is stored in the variable digit.
Now, digit contains the last digit of num, that is4Then, multiply the digit by10After that, add it to the reverse variable. Multiply by10A new position will be added to the reverse number.
multiplied by one-tenth10can get the tenth digit, the one-tenth can get the percentage, and so on. In this case, reversed contains 0 * 10 + 4 =4.
Then num divided by10, so now it only contains the first three digits:123.
After the second iteration, digit equals3, reversed equals4 * 10 + 3 = 43and num= 12
After the third iteration, digit equals2, reversed equals43 * 10 + 2 = 432and num= 1
After the fourth iteration, digit equals1, reversed equals432 * 10 +1 = 4321and num= 0
Now num= 0, so the test expression num != 0 fails and the while loop exits. reversed already contains the reversed number4321.
This is the equivalent Java code:Java Program to Reverse a Number