Java Solution: Beats 81%


  • 0
    J
    public class Solution {
        public boolean isHappy(int n) {
            
            if (n  < 1) {return false;}
            boolean firstPass = true;
            int result = 0;
            
            while (result != 1 && result != n) {
                if (firstPass) {
                    result = n;
                    n = 4;
                    firstPass = false;
                }
                result = checkNum(result);
            }
            
            if (result == 1) {
                return true;
            }
            else {
                return false;
            }
        }
        
        public int checkNum(int n) {
            int length = String.valueOf(n).length();
            int[] nums = new int[length];
            int result = 0;
            
            for (int i = 0; i < length; i++) {
                nums[i] = n % 10;
                n *= .1;
                nums[i] *= nums[i];
                result += nums[i];
            }
            
            return result;
        }
    }
    

  • 0

    Hi, Why 'n = 4;'?


  • 0
    J

    @382259185-qq-com I haven't gone through the math to figure out why, but while testing I found out that every number that loops will start it's loop at 4. So if it is past it's first pass and hits 4, it is not a 'happy' number.


Log in to reply
 

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