I am working on an easy math question Happy number Happy Number - LeetCode
- Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example:
Input: 19 Output: true Explanation: 1² + 9² = 82 8² + 2² = 68 6² + 8² = 100 1² + 0² + 0² = 1
My solutions
Solution 1, 28ms 12.1mb
- string operations
class Solution1:
def isHappy(self, n):
s = set()
while n != 1:
if n in s: return False
s.add(n)
n = sum([int(i) ** 2 for i in str(n)])
else:
return True
- Solution 2, 24ms, 12.3mb
class Solution2:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
s = set()
while n != 1:
if n in s: return False
s.add(n)
_sum = 0
while n:
_sum += (n % 10) ** 2
n //= 10
n = _sum
return n == 1
- Solution 3 the save as solution 2 minor changes (24ms, 12.3mb)
class Solution3:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
s = set()
while n:
if 1 in s:
return True
if n in s:
return False
s.add(n)
_sum = 0
while n:
_sum += (n%10)**2 #leave unit digit
n //= 10 #remvoe unit digit
n = _sum
- Solution 4 without extra space(24ms, 12.3mb)
class Solution4:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
while n != 1 and n != 4:
_sum = 0
while n :
_sum += (n % 10) * (n % 10)
n //= 10
n = _sum
return n == 1
TestCase
class MyCase(unittest.TestCase):
def setUp(self):
self.solution = Solution3()
def test_1(self):
n = 19
check = self.solution.isHappy(n)
self.assertTrue(check)
It's interesting that the last 3 solutions shared the same performance, though try best possibility to improve it.