Recursive solution using a map. Takes 5ms


  • 0
    M
    public class Solution {
        Map<Integer, Boolean> myMap = new HashMap<Integer, Boolean>();
        public boolean isHappy(int n) {
            if(myMap.containsKey(n)){
                return false;
            }
            myMap.put(n, true);
            int formedNumber = 0;
            while(n>0){
                int lastDigit = n%10;
                formedNumber = formedNumber + (lastDigit*lastDigit);
                n = n/10;
            }
            if(formedNumber==1){
                return true;
            }
            return isHappy(formedNumber);
        }
    }

Log in to reply
 

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