In this tutorial, you shall learn how to check if a given string or number is a palindrome or not in Kotlin, with example programs.
Kotlin – Palindrome string or number
A string or number is said to be a palindrome if it is same as that of its reversed value.
Therefore, to check if given string or number is a palindrome, compare the given value to its reversed value. If both are same, then the given value is a palindrome, or else not.
In this tutorial, we will learn how to check if a string, or number, is a palindrome or not with example programs.
Palindrome String Program
In the following program, we read a string str
from user and check if this string is a palindrome or not.
Main.kt
fun main() {
print("Enter a string : ")
val str = readLine()!!
if (str == str.reversed()) {
print("$str is palindrome.")
} else {
print("$str is not palindrome.")
}
}
Output #1
Enter a string : racecar
racecar is palindrome.
Output #2
Enter a string : helloworld
helloworld is not palindrome.
Related tutorials for the above program
Palindrome Number Program
In the following program, we read an integer number n
from user and check if this number is a palindrome number or not.
Main.kt
fun main() {
print("Enter an integer : ")
val n = readLine()!!.toInt()
if (n == n.toString().reversed().toInt()) {
print("$n is palindrome.")
} else {
print("$n is not palindrome.")
}
}
Output #1
Enter an integer : 12321
12321 is palindrome.
Output #2
Enter an integer : 123456
123456 is not palindrome.
Related tutorials for the above program
- Kotlin – Reverse a number
- Kotlin – Convert integer to string
- Kotlin – Reverse a string
- Kotlin – Convert string to integer
Conclusion
In this Kotlin Tutorial, we learned how to check if given string or number is a palindrome or not.