Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Kotlin Program to Reverse a Number
In this article, we will understand how to print an integer in Kotlin. The reverse of a number is computed using a loop and arithmetic operator % and /.
Below is a demonstration of the same ?
Suppose our input is ?
The number : 123456
The desired output would be ?
The result is 654321
Algorithm
Step 1 ? START
Step 2 ? Declare two integer values namely myInput and reversed.
Step 3 ? Define the values
Step 4 ? Run a while loop
Step 5 ? Use modulus of 10 and get remainder for ?myTemp? .
Step 6 ? Multiply ?reversed? with 10, and add to ?myTemp?, and make that the current ?reversed?.
Step 7 ? Divide ?myInput? by 10, and make that the current ?myInput'.
Step 8 ? Display the result
Step 9 ? Stop
Example 1
In this example, we will reverse a number using a while loop. First, let us declare a variable for the input i.e. the number we will reverse. We have also declared a variable for the output i.e. reversed number ?
var myInput = 123456 var reversed = 0
Now, using a while loop reverse the number. Loop till the input != 0;
while (myInput != 0) {
val myTemp = myInput % 10
reversed = reversed * 10 + myTemp
myInput /= 10
}
Let us now see the complete example to reverse a number using a while loop ?
fun main() { var myInput = 123456 var reversed = 0 println("The number is defined as: $myInput") while (myInput != 0) { val myTemp = myInput % 10 reversed = reversed * 10 + myTemp myInput /= 10 } println("The reversed number is: $reversed") }
Output
The number is defined as: 123456 The reversed number is: 654321
Example 2
In this example, we will reverse a number.
fun main() { var myInput = 123456 println("The number is defined as: $myInput") reverseNumber(myInput) } fun reverseNumber(input: Int) { var myInput = input var reversed = 0 while (myInput != 0) { val myTemp = myInput % 10 reversed = reversed * 10 + myTemp myInput /= 10 } println("The reversed number is: $reversed") }
Output
The number is defined as: 123456 The reversed number is: 654321
