Modular code with the underlying logic of using a set


  • 0
    S
    public class Solution {
        public boolean isHappy(int n) {
            Set<Integer> prevRes = new HashSet<>();
            ArrayList<Integer> digits = getDigits(n);
            return _isHappy(digits,prevRes);
            
        }
        private static ArrayList<Integer> getDigits(int n){
            ArrayList<Integer> res = new ArrayList<>();
            while(n!=0){
                res.add(n%10);
                n/=10;
            }
            return res;
        }
        private static boolean _isHappy(ArrayList<Integer> digits,Set<Integer> prevRes){
            int happySum =0;
            for(int i=0;i<digits.size();i++){
                happySum+=Math.pow(digits.get(i),2);
            }
            
            if(happySum==1) return true;
            if(prevRes.contains(happySum))
              return false;  
            prevRes.add(happySum);
            ArrayList<Integer> nextdigits = getDigits(happySum);
            return _isHappy(nextdigits,prevRes);
            
            
            
        }
    }
    

Log in to reply
 

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