// Function to check if a number is a palindrome in a given base
public class PalindromeChecker {
public static boolean isPalindrome(int num, int base) {
if (base < 2) return false; // Invalid base
StringBuilder strnumreversed = new StringBuilder();
int temp = num;
// Convert number to string in given base
do {
int digit = temp % base;
strnumreversed.append(digit < 10 ? (char) ('0' + digit) : (char) ('A' + (digit - 10)));
temp /= base;
} while (temp > 0);
// Check palindrome
String strnum = strnumreversed.toString();
String reversed = strnumreversed.reverse().toString();
return strnum.equals(reversed);
}
public static void main(String[] args) {
int limit = 1000;
System.out.println("Numbers that are palindromes in both base 10 and base 2:");
for (int i = 1; i <= limit; i++) {
if (isPalindrome(i, 10) && isPalindrome(i, 2)) {
System.out.print(i + " (binary: ");
// Print binary representation
StringBuilder binary = new StringBuilder();
int temp = i;
do {
binary.append((temp % 2) == 1 ? '1' : '0');
temp /= 2;
} while (temp > 0);
binary.reverse();
System.out.println(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)
*/