Happy Number

Leetcode202

Example,

Question: Return true if the sum of all squared number of n can eventually becomes 1, else return false

Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Solution 1: Two while loops, first while loop to check if the total sum has been calculated before, another while loop to find out the total sum of all the sqaured number of n

time complexiity: O(d) number of digits
space complexity: O(k) hash set
runtime: 32 ms
memory: 12.8 MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def isHappy(self, n: int) -> bool:
memo = set()
while True:
totalSum = 0

while n > 0:
currentNumber = n % 10
totalSum += currentNumber * currentNumber
n //= 10

if totalSum == 1:
return True

if totalSum in memo:
return False

n = totalSum
memo.add(totalSum)

I’m being harassed by my ex,

it sucks.