Kotlin Program to Reverse a Number

In this tutorial, you will learn two different ways to reverse a number in Kotlin with program examples.

Method 1: Using reversed() & String

fun main() {
    var num = 13436
    var str = num.toString()
    var reversedString = str.reversed()
    num = reversedString.toInt()
    print(num)
}

In this method, we are first converting the integer number to a string. Then reversing the string using reversed() function. Finally converting the reversed string back to an integer.

Method 2: Using Loop, Modulo, and Division

fun main() {
    var num = 13436
    var reversedNum = 0

    while (num != 0) {
        reversedNum = reversedNum * 10 + (num % 10)
        num /= 10
    }

    print(reversedNum)
}

In this method, we used a while loop to extract each digit of the number by using the modulo operator (%) to get the remainder when divided by 10, and then the division operator (/) to remove the last digit. The extracted digits are then used to make the reversed number.

If you have any queries ask in the comment section below.

Leave a Comment

Your email address will not be published. Required fields are marked *