Java solution


  • 0
    T

    store all calculating numbers in a hashset and check every time if we are in a cycle

    public class Solution {
        public boolean isHappy(int n) {
            //if(n>10&&n%10==0) return true;
            Set<Integer> set = new HashSet();
            set.add(n);
            int sum = divideDigits(n);
            while(sum!=1){
                if(set.contains(sum)) return false;
                else{
                    set.add(sum);
                    sum=divideDigits(sum);
                }
            }
            
            return true;
            
        }
        
        
        public int divideDigits(int n){
            if(n==0) return 0;
            int sum = 0;
            
            int yu =0;
            while(n!=0){
                yu = n%10;
                n=n/10;
                sum = sum + yu*yu;
            }
            return sum;
        }
    }
    

Log in to reply
 

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