5ms AC Java solution


  • 0
    C
    public class Solution {
        public boolean isHappy(int n) {
            return isHappy(n, 0);
        }
        
        public boolean isHappy(int n, int c) {
            if(n == 1){
                return true;
            }
            
            if(n == Integer.MAX_VALUE || c > 32){ // To prevent stack overflow
                return false;
            }
            
            int sum = 0;
            
            while(n > 0){
                sum += Math.pow(n%10, 2);
                n = n/10;
            }
            
            return isHappy(sum, ++c);
        }
    }

Log in to reply
 

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