Tuesday, August 25, 2015

Leetcode 202. Happy Number

https://leetcode.com/problems/happy-number/

Easy problem. Just use some recursion.

Solution:
# T:O(k) S:O(k)
class Solution:
    # @param {integer} n
    # @return {boolean}
    def perform(self, n):
        ret = 0
        while n:
            ret += (n%10)**2
            n /= 10
        return ret
        
    def isHappy(self, n):
        lst = []
        while True:
            if self.perform(n) == 1:
                return True
            if n not in lst:
                lst.append(n)
            n = self.perform(n)
            if n in lst:
                return False
Run Time: 48 ms

No comments:

Post a Comment