Project Euler #36: Double-base palindromes

  • + 0 comments

    JAva Code

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        
        static String valid(int n, int k) {
            StringBuilder s = new StringBuilder();
            while (n > 0) {
                int r = n % k;
                n /= k;
                s.append(Integer.toString(r));
            }
            return s.reverse().toString();
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String[] input = scanner.nextLine().split(" ");
            int n = Integer.parseInt(input[0]);
            int k = Integer.parseInt(input[1]);
            int t = 0;
    
            for (int i = 1; i <= n; i++) {
                String strI = Integer.toString(i);
                if (strI.equals(new StringBuilder(strI).reverse().toString())) {
                    String validStr = valid(i, k);
                    if (validStr.equals(new StringBuilder(validStr).reverse().toString())) {
                        t += i;
                    }
                }
            }
    
            System.out.println(t);
            scanner.close();
        }
    }