Project Euler #55: Lychrel numbers

  • + 0 comments

    Java 8

    import java.io.; import java.util.;

    public class Solution {

    public static boolean isPalindrom(long a){
        long num=a,res=0;
        while (num!=0)
        {
            res= res*10+num%10; 
            num /=10;
        }     
        return (res==a)?true:false;
    }
    
    public static long reverse(long a){
        long res=0;
        while (a!=0)
        {
            res= res*10+a%10; 
            a /=10;
        }     
        return res;
    }
    
    
    public static long LychrelNumber(long data){
        int count =0;
        long res=data;
        while(count<60)
        {
            if(isPalindrom(res)) return res;
            res= res + reverse(res);
            count++;           
        }
    
        return -1;
    }
    
    public static void main(String[] args) {
    
        Scanner s = new Scanner(System.in);
        int data = s.nextInt();
    
        HashMap<Long, Integer> map =new HashMap<>();
        int maxCount=0;
        long maxLychrel=0;
    
        for(int i=1; i<=data;i++)
        {
            long temp= LychrelNumber(i);
            if(temp != -1)
            {
                 map.put(temp, map.getOrDefault(temp, 0) + 1);
    
                if(map.get(temp) > maxCount) 
                {maxCount = map.get(temp);
                 maxLychrel= temp;}
            }
    
        }
    
        System.out.println(maxLychrel + " " + maxCount); 
    }
    

    }