How to find a list of numbers up to a limit that is a palindrome in base 10 and base 2 in Kotlin

1 Answer

0 votes
fun main() {
    val limit = 1000

    println("Numbers that are palindromes in both base 10 and base 2:")
    for (i in 1..limit) {
        if (isPalindrome(i, 10) && isPalindrome(i, 2)) {
            print("$i (binary: ")

            // Print binary representation
            var temp = i
            val binary = StringBuilder()
            do {
                binary.append(if (temp % 2 == 1) '1' else '0')
                temp /= 2
            } while (temp > 0)
            println(binary.reverse().toString() + ")")
        }
    }
}

// Function to check if a number is a palindrome in a given base
fun isPalindrome(num: Int, base: Int): Boolean {
    if (base < 2) return false // Invalid base

    val strnumReversed = StringBuilder()
    var temp = num

    // Convert number to string in given base
    do {
        val digit = temp % base
        strnumReversed.append(
            if (digit < 10) ('0'.code + digit).toChar()
            else ('A'.code + (digit - 10)).toChar()
        )
        temp /= base
    } while (temp > 0)

    // Check palindrome
    return strnumReversed.toString() == strnumReversed.reversed().toString()
}



/*
run:

Numbers that are palindromes in both base 10 and base 2:
1 (binary: 1)
3 (binary: 11)
5 (binary: 101)
7 (binary: 111)
9 (binary: 1001)
33 (binary: 100001)
99 (binary: 1100011)
313 (binary: 100111001)
585 (binary: 1001001001)
717 (binary: 1011001101)

*/

 



answered 1 day ago by avibootz
...