Kotlin program to reverse a number

Kotlin | Reverse number: Here, we are going to learn how to reverse a given number in Kotlin programming language? Submitted by IncludeHelp, on April 20, 2020

Problem statement

Given an integer number, we have to find reverse number and print it.

Example

Input:
Number: 12345

Output:
Reverse Number: 54321

Kotlin - Reverse a number

To find a reverse number – we use this formula: reverse = (reverse * 10) + lastDigit, to calculate the lastDigit, we find the remainder of the number by dividing the number with 10.

Program to reverse a number in Kotlin

Consider the below program to find the reverse number.

package com.includehelp.basic

import java.util.*

/* Function to Reverse an given Integer Number */
fun getReverse(number: Int): Int {
    var number = number
    var sum = 0
    
    while (number > 0) {
        val r = number % 10
        sum = sum * 10 + r
        number /= 10
    }
    return sum
}


//Main function Entry Point of Program
fun main(arg: Array<String>) {
    val sc = Scanner(System.`in`)
    
    //Input Number
    println("Enter Number  : ")
    val num: Int = sc.nextInt()
    
    //Calling function to get reverse number
    val reverseNumber = getReverse(num)
    
    // Print reverse format of number
    println("Reverse Number : $reverseNumber")
}

Output

Run 1:
Enter Number  :
12345
Reverse Number : 54321
-------
Run 2:
Enter Number  :
345389
Reverse Number : 983543

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.