English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn how to check if a number is a palindrome in Kotlin. This is done by using a while loop.
fun main(args: Array<String>) { var num = 121 var reversedInteger = 0 var remainder: Int val originalInteger: Int originalInteger = num //The reversed integer is stored in the variable while (num != 0) { remainder = num % 10 reversedInteger = reversedInteger * 10 + remainder num /= 10 } //If orignalInteger and reversedInteger are equal, then it is a palindrome if (originalInteger == reversedInteger) println("$originalInteger is a palindrome.") else println("$originalInteger is not a palindrome.") }
When running this program, the output is:
121 Is a palindrome.
Note:You can change the value of num to11221Then, when running the program, the output is:
11221 Is not a palindrome.
The following is the equivalent Java code:Check the Java program for palindrome numbers
In this program
First, the value of the given number (num) is stored in another integeroriginalIntegerin the variable. This is because we need to compare the value of the reversed number with the original number at the end.
Then, use a while loop to iterate over num until it equals 0.
In each iteration, the last digit of num is stored in remainder.
Then, add the remainder to reversedInteger, so that it can be added to the next position value (multiply by10).
Then, divide by10Then, remove the last digit from num.
Finally, compare reversedInteger and originalInteger. If they are equal, then it is a palindrome number. If not, then it is not.
The following are the steps to be executed:
num | num != 0 | remainder | reversedInteger |
---|---|---|---|
121 | True | 1 | 0 * 10 +1 = 1 |
12 | True | 2 | 1 * 10 + 2 = 12 |
1 | True | 1 | 12 * 10 +1 = 121 |
0 | False | -- | 121 |