Java recursive solution beat 94%


  • 0
    R

    Base case is n process to less then 10, and judge if it is a happy number.

    public class Solution {
        public boolean isHappy(int n) {
            if(n<10&&n!=1&&n!=7) return false;
            if(n==1||n==7) return true;
            int sum = 0;
            while(n>0){
                int digit = n%10;
                sum = sum + digit*digit;
                n/=10;
            }
            return isHappy(sum);
            
        }
    }
    

Log in to reply
 

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