You can not select more than 25 topics
Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
- #1.9 快乐数:编写一个算法来判断一个数 n 是不是快乐数。如果 n 是快乐数打印True ;不是,则打印输出False。
- #「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
-
- num = 19
- #结果历史,判断是否陷入无限循环
- oper_list = [num]
- while 1:
- oper = 0
- for i in range(1,len(str(num))+1):
- oper += (num//10**(i-1)%10) ** 2#从右至左第i位上数字的平方
- num = oper
-
- if num == 1:
- print('true')
- oper_list.append(oper)
- break
- elif num in oper_list:
- print('false')
- oper_list.append(oper)
- break
- else:
- oper_list.append(oper)
-
- print(oper_list)
|