Happy Number - Leetcode 202 - Python

preview_player
Показать описание
FAANG Coding Interviews / Data Structures and Algorithms / Leetcode
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

That way 82, …., 100 all are happy number too 🗿

_greysama_
Автор

a better way is to check if the new number after squaring the digits is 4, if it is 4 then it is not a happy number. It doens't reduce the time comp, but makes the space comp O(1)

BoringAhhBoy
Автор

You can do the first one recursively as well, just create a helper function that takes n and the seen set, which returns True when n is 1, False when n is in seen, otherwise check if the next n is happy with the current n added to seen. This is a valid tail recursion, so it can benefit from TCO. (Not that Python supports it...)

```
def isHappy(self, n: int) -> bool:
def helper(n, seen):
return (
True if n == 1 else
False if n in seen else
helper(
sum([int(d) ** 2 for d in str(n)]),
seen | set([n])
)
)
return helper(n, set())
```

alxjones
Автор

Should I make an exercise called grumpy numbers? And another one called habanero numbers? Would that work?

jesprotech
Автор

Why is having an ending happy while being infinite is unhappy? I would have switched it.

kkiimm
Автор

bool isHappy(int n) {
if(n==1) return true;
while(true)
{
if(n == 89)
return false;
if(n == 1)
return true;
n = sqr(n);
}
return false;
}

BCS-IshtiyakAhmadKhan