Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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

1 Answer

0 votes
#include <iostream>
#include <algorithm> // reverse
#include <string>

// Function to check if a number is a palindrome in a given base
bool isPalindrome(unsigned int num, unsigned int base) {
    if (base < 2) return false; // Invalid base

    std::string strnumreversed;
    unsigned int temp = num;

    // Convert number to string in given base
    do {
        unsigned int digit = temp % base;
        strnumreversed.push_back(digit < 10 ? '0' + digit : 'A' + (digit - 10));
        temp /= base;
    } while (temp > 0);


    // Check palindrome
    std::string strnum = strnumreversed;
    std::reverse(strnum.begin(), strnum.end());

    return strnumreversed == strnum;
}

int main() {
    unsigned int limit = 1000;

    std::cout << "Numbers that are palindromes in both base 10 and base 2:\n";
    for (unsigned int i = 1; i <= limit; i++) {
        if (isPalindrome(i, 10) && isPalindrome(i, 2)) {
            std::cout << i << " (binary: ";

            // Print binary representation
            unsigned int temp = i;
            std::string binary;
            do {
                binary.push_back((temp % 2) ? '1' : '0');
                temp /= 2;
            } while (temp > 0);
            std::reverse(binary.begin(), binary.end());

            std::cout << binary << ")\n";
        }
    }
}



/*
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 Nov 10, 2025 by avibootz
...