Skip to main content

How to check if a number is a palindrome in binary representation in Kotlin

How to check if a number is a palindrome in binary representation in Kotlin.

Here's a step-by-step tutorial on how to check if a number is a palindrome in binary representation using Kotlin:

Step 1: Convert the Number to Binary

The first step is to convert the given number to its binary representation. In Kotlin, you can use the toString(radix: Int) function to convert a number to a specified radix (base). In this case, the radix will be 2 for binary representation.

fun toBinary(number: Int): String {
return number.toString(2)
}

Step 2: Check if the Binary Representation is a Palindrome

Once you have the binary representation of the number, you need to check if it is a palindrome. A palindrome is a string that reads the same forwards and backward.

In Kotlin, you can check if a string is a palindrome by comparing it with its reversed version. If the two strings are equal, then it is a palindrome.

fun isPalindrome(str: String): Boolean {
return str == str.reversed()
}

Step 3: Check if the Number is a Palindrome in Binary Representation

Now, you can combine the above two functions to check if a given number is a palindrome in binary representation.

fun isBinaryPalindrome(number: Int): Boolean {
val binary = toBinary(number)
return isPalindrome(binary)
}

Step 4: Test the Function

To test the isBinaryPalindrome() function, you can call it with different numbers and check the output.

fun main() {
val numbers = listOf(5, 10, 15, 21, 32)

for (number in numbers) {
val isPalindrome = isBinaryPalindrome(number)
if (isPalindrome) {
println("$number is a binary palindrome")
} else {
println("$number is not a binary palindrome")
}
}
}

Output:

5 is a binary palindrome
10 is not a binary palindrome
15 is a binary palindrome
21 is not a binary palindrome
32 is not a binary palindrome

In the above example, the numbers 5 and 15 are palindromes in binary representation, while the numbers 10, 21, and 32 are not.

That's it! You have successfully checked if a number is a palindrome in binary representation using Kotlin.