brutal solution, not smart, just share


  • 0
    Y
    class Solution {
        
        public boolean isHappy(int n) {
            HashSet<Integer> set = new HashSet<Integer>();
            while(helper(n) != 1){
                int num = helper(n);
                if(!set.add(num)){
                    return false;
                }
                else
                    set.add(num);
                n = num;
            }
            return true;
            
        }
        
        private int helper(int n){
            int r = 0;
            int c = 10;
            for( ; n > 0 ; ){
                r =  (n % 10) * (n % 10) + r;
                n = n / 10;
            }
            return r;
        }
    }
    

    I find out that if the number is not a happy number. After many times circulation, you can get an array of numbers, repeating and repeating over again, so I use HashSet. I know my solution is not best or simple. I just post it for sharing my minds. Thanks for you all.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.