We will go through kotlin program to reverse a number.
For example,
Input:
1234Output:
4321
Input:
1232Output:
2321
1. Program to Reverse a number
Sourcecode –
import java.util.* fun main() { val read = Scanner(System.`in`) println("Enter n:") var n = read.nextInt() var reverseN = 0 while (n != 0) { val remainder = n % 10 reverseN = reverseN * 10 + remainder n /= 10 } println("Reversed N = $reverseN") }
When you run the program, output will be
Enter n: 12345 Reversed N = 54321
Explanation:
Let’s assume we have entered n = 123
Now,
At 1st iteration,
n = 123, reverseN = 0(123 != 0) is true. So, while loop will be executed.
Inside while loop,
remainder = 123 % 10 => remainder = 3
reverseN = reverseN * 10 + remainder => reverseN = 0 * 10 + 3 => reverseN = 3
n /= 10 => n = n / 10 => n = 123 / 10 => n = 12After 1st iteration,
n = 12, reverseN = 3
At 2nd iteration,
n = 12, reverseN = 3(12 != 0) is true. So, while loop will be executed.
Inside while loop,
remainder = 12 % 10 => remainder = 2
reverseN = reverseN * 10 + remainder => reverseN = 3 * 10 + 2 => reverseN = 32
n = n / 10 => n = 12 / 10 => n = 1After 2nd iteration,
n = 1, reverseN = 32
At 3rd iteration,
n = 1, reverseN = 32(1 != 0) is true. So, while loop will be executed.
Inside while loop,
remainder = 1 % 10 => remainder = 1
reverseN = reverseN * 10 + remainder => reverseN = 32 * 10 + 1 => reverseN = 321
n = n / 10 => n = 1 / 10 => n = 0After 3rd iteration,
n = 0, reverseN = 321
At 4th iteration,
n = 0, reverseN = 321(0 != 0) is false. So, while loop will be exited.
So, finally reverseN is our reversed number for given number.
You can apply the same logic for any other number.
Thus, we went through Kotlin program to reverse a number