1. When you need to quickly determine whether an element appears in a sequence , a hash table is used.
2. The summary question type targeted in this article is whether there is a cycle in a given sequence or a sequence that needs to be constructed, which is the same as the question type in 160. Intersecting Linked List , 141. Circular Linked List , and 142. Circular Linked List II .
202. Happy Number
This question also examines how to find the sum of the squares of the numbers in each position for positive integers.
'''
202. 快乐数
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:
对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
如果这个过程 结果为1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
示例 1:
输入:n = 19
输出:true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 = 1
题眼:无限循环:当同一个数字出现第二次之后,就说明存在环
思路:这道题和环形链表的题目一样,模拟上述过程,并用哈希表记录数值;
'''
class Solution:
def isHappy(self, n: int) -> bool:
hashTable = set()
hashTable.add(n)
while True:
n = self.getSum(n)
if n == 1:
return True
elif n in hashTable:
return False
else:
hashTable.add(n)
# 这道题还考察如何对正整数求解各个位置数字的平方和
def getSum(self, n: int) -> int:
s = 0
while n > 0:
s += (n % 10) * (n % 10) # 总是获取数字的最后一位
n //= 10
return s
if __name__ == "__main__":
obj = Solution()
while True:
try:
n = int(input().strip().split('=')[1].strip())
print(obj.isHappy(n))
except EOFError:
break