public class Solution { private int SumSqares(int n) { //将一个数字的各个数位的值分开存储 var list = new List<int>(); do { var x = n % 10; list.Add(x); n = n / 10; } while (n != 0); var sum = 0; foreach (var l in list) { sum += l * l; } return sum; } public bool IsHappy(int n) { var list = new List<int>();//已经计算出来的值,用于判断是否出现循环 while (n != 1 && !list.Contains(n)) { list.Add(n); n = SumSqares(n); } if (n == 1) { return true; } else { return false; } } }
https://leetcode.com/problems/happy-number/#/description
补充一个python的实现:
1 class Solution: 2 def isHappy(self, n: int) -> bool: 3 s = set([n]) 4 while n != 1: 5 sn = str(n) 6 sums = 0 7 for i in range(len(sn)): 8 sums += int(sn[i]) ** 2 9 if sums in s: 10 return False 11 s.add(sums) 12 n = sums 13 return True
使用集合s记录已经出现过的数字:
如果出现数字1,则返回True;
如果在出现重复的数字之前都没有出现过1,则返回False。