Search code examples
javaradixpalindrome

Java: Palindrome in both bases


Okay so I have no idea about how to do this problem! I need to write a code that will find the sum of all numbers less than 1 million that are palindromes in both base 10 and base 2.

Could someone please help me get this problem started!


Solution

  • The solution is pretty forward, it's just a bruteforce over all palindrome numbers bellow 1M.

    public class Main {
    
    
        public static void main(String[] args) {
    
            int count=0;
            for (int i = 0; i < 1_000_000; i++) {
                if (isDoublePalindrome(""+i)) {
                    count+=i;
                }
            }
    
            System.out.println(count);
    
        }
    
         public static boolean isPalindrome(String N){
            return new StringBuilder(N).reverse().toString().equals(""+N);
        }
    
        public static String toBinary(String N){
    
            return Long.toBinaryString(Long.parseLong(N));
        }
    
        public static boolean isDoublePalindrome(String N){
    
            if(isPalindrome(N) && isPalindrome(toBinary(N))) return true;
            return false;
        }
    
    }