有三种情况:
- 最终是1
- 最终进入一个循环
- 一直增加,到无穷大(这种情况不可能,例如9999999999999,下一个数为1053)
算法如下:
- 给定n,求下一个数
- 检测是否已经出现过(成为环),利用哈希表(Python字典或者集合)
class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
seen = set()
while n not in seen:
seen.add(n)
n = self.get_next(n)
return n == 1
def get_next(self, n):
total = 0
while n > 0:
n, digit = divmod(n, 10)
total += digit ** 2
return total
class Solution:
def isHappy(self, n):
seen = set()
while n not in seen:
seen.add(n)
n = sum(int(i) ** 2 for i in str(n))
return n == 1
Go
package main
func isHappy(n int) bool {
seen := make(map[int]bool)
for n != 1 && !seen[n] {
seen[n] = true
n = getNext(n)
}
return n == 1
}
func getNext(n int) int {
next := 0
for n != 0 {
next += (n % 10) * (n % 10)
n /= 10
}
return next
}
class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
slow = n
fast = self.get_next(n)
while fast != 1 and slow != fast:
slow = self.get_next(slow)
fast = self.get_next(self.get_next(fast))
return fast == 1
def get_next(self, n):
total = 0
while n > 0:
n, digit = divmod(n, 10)
total += digit ** 2
return total
Go
func isHappy(n int) bool {
slow, fast := n, getNext(n)
for fast != 1 && slow != fast {
slow = getNext(slow)
fast = getNext(getNext(fast))
}
return fast == 1
}
func getNext(n int) int {
next := 0
for n != 0 {
next += (n % 10) * (n % 10)
n /= 10
}
return next
}