My code that beats 97.48% and isn't based on detecting a loop, O(1) space


  • 0
    L

    // I played with the numbers and found that an arbitrary number will reach either 1 or 4 if we keep doing square sum. Hitting 4 means it's in a infinite loop.
    // e.g. 4 -> 16->37->58->89->145->42->20->4
    // e.g. 3->9->81->65->61->37->58->....->4

      public class Solution {
              //If we keep square sum of an arbitrary number, we will either get 1 or 4. 
             public boolean isHappy(int n) {
                   if(n < 0) n  = -n;
                   if(n == 1) return true;
                   if(n == 4 | n == 0) return false;
                  while(n != 1 | n != 4){
                       n = digitSquareSum(n);
                       if(n == 1) return true;
                      if(n == 4) return false;
                  }
              return n == 1 ? true:false;
        
          }
    
    private int digitSquareSum(int n){
        int x = 0;
        while(n > 0){
            int digit = n % 10;
            x += (digit * digit);
            n /= 10;
        }
        return x;
    }
    

    }


Log in to reply
 

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