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

1 Answer

0 votes
// Function to check if a number is a palindrome in a given base
function isPalindrome(num: number, base: number): boolean {
    if (base < 2) return false; // Invalid base

    let strnumReversed: string = '';
    let temp: number = num;

    // Convert number to string in given base
    do {
        const digit = temp % base;
        strnumReversed += digit < 10
            ? String.fromCharCode('0'.charCodeAt(0) + digit)
            : String.fromCharCode('A'.charCodeAt(0) + (digit - 10));
        temp = Math.floor(temp / base);
    } while (temp > 0);

    // Check palindrome
    return strnumReversed === strnumReversed.split('').reverse().join('');
}

function printBinary(num: number): string {
    let binary: string = '';
    let temp: number = num;

    // Print binary representation
    do {
        binary += temp % 2 ? '1' : '0';
        temp = Math.floor(temp / 2);
    } while (temp > 0);

    return binary.split('').reverse().join('');
}


const limit = 1000;

console.log("Numbers that are palindromes in both base 10 and base 2:");
for (let i = 1; i <= limit; i++) {
    if (isPalindrome(i, 10) && isPalindrome(i, 2)) {
        const binary = printBinary(i);
        console.log(`${i} (binary: ${binary})`);
    }
}



/*
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
...