My Python solution, 48ms


  • 0
    S
    class Solution(object):
        def isHappy(self, n):
    
            if n == 1:
                return True;
        
            elif n == 4: 
                return False;
            
            return self.isHappy(sumDigitSquares(n));
            
    def leastSignificantDigit(num):
        return num % 10;
    
    
    def hasDigitsRemaining(num):
        return (num // 10) != 0;
        
    
    
    def sumDigitSquares(num):
        
        sum = 0;
        
        while hasDigitsRemaining(num):
            sum += leastSignificantDigit(num)**2
            num //= 10;
            
        
        sum += num**2
        return sum;

  • 0
    G

    hasDigitsRemaining could be simply implemented as:

    return num >= 10
    

    but probably the best thing to do would be to rewrite the while loop as:

    sum = 0
    while num:
        sum += leastSignificantDigit(num)**2
        num //= 10
    return sum

Log in to reply
 

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