Kotlin Program to Check Number is Palindrome or Not

Write a Kotlin Program to Check a given number is palindrome or not.

For example,

 Input:
 1122

 Output:
 1122 is not palindrome
 Input:
 12321

 Output
 12321 is palindrome

1. Program to Check Whether Number is Palindrome

Sourcecode –

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter n:")
    var n = read.nextInt()

    val origN = n
    var reverseN = 0
    while (n != 0) {
        val remainder = n % 10
        reverseN = reverseN * 10 + remainder
        n /= 10
    }

    val result = if(reverseN == origN) "$origN is palindrome" else "$origN is not palindrome"
    println(result)
}

When you run the program, output will be –

Enter n:
32324
32324 is not palindrome
 
Explanation:

We can check whether number is palindrome or not by comparing original and it’s reversed number.

For example,
Let’s assume n = 123.
It’s reversed number will be 321.
Since 321 is not equal to 123, 123 is not palindrome.

Let’s take another example,
n = 12321
It’s reversed number will be 12321.
Since 12321 (original) is equal to 12321 (reversed number), 12321 is palindrome.

In our program, we

– stored original number in variable origN
– reversed n and stored it in variable reverseN

Then, we compared origN and reverseN to check for palindrome

Thus, we went through Kotlin Program to check number is palindrome or not.

Leave a Reply