Write an algorithm to determine if a number n
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.
- 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.
Return true
if n
is a happy number, and false
if not.
Example 1:
Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
Example 2:
Input: n = 2 Output: false
Constraints:
1 <= n <= 231 - 1
解法1:
看完题目直观的解法是一直计算下去直到等于1停止。难点是如果一直不等于1,那应该什么时候停止呢。我们知道永不停止有两种情况:
1. 进入一个环后无限循环,这种情况好判断,只要后面遇到前面出现过的数字,那就说明是一个环。
2. 数字一直变大直到无穷大。其实这种情况不会出现,我们来看一个例子,一个10位的数最大的就是9999999999,那它的下一个数就是(9*9)*10 = 810变成一个3位数;3位数最大的是999,下一个数是81 * 3 = 243。因此可以得到一个结论,到达3位数之后就不可能再变成4位以上的数,也就不可能变成无穷大。
这样题目就可以简化为判断最终是到达1还是进入一个环。
class Solution:
def isHappy(self, n: int) -> bool:
seen = set()
while n > 1 :
if n in seen :
return False
seen.add(n)
tmp = 0
while n > 0 :
tmp += (n % 10) ** 2
n //= 10
n = tmp
return True
这题时间复杂度计算也是个难点,时间复杂度取决于位数(一个数的位数lg(n)),对于数n第一轮时间是lg(n),另外我们知道随着循环进行位数降的很快。
因此这种解法的时间和空间复杂度都是O(lg(n))
解法2:
根据解法一的分析,我们其实是去判断是否存在一个环,这就跟另外一道题(141. Linked List Cycle)很像,判断一个链表里是否存在一个环。因此这道题也可以相同方法即快慢指针的方法。
class Solution:
def isHappy(self, n: int) -> bool:
def getNext(n) :
nextNum = 0
while n > 0 :
nextNum += (n % 10) ** 2
n //= 10
return nextNum
slow = n
fast = getNext(n)
while fast > 1 and slow != fast:
slow = getNext(slow)
fast = getNext(getNext(fast))
return fast == 1
空间复杂度变成了O(1)