diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 5704283d..d7a6b4e9 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -215,6 +215,23 @@ var isHappy = function(n) { } return n === 1; }; + +// 方法四:使用Set(),求和用reduce +var isHappy = function(n) { + let set = new Set(); + let totalCount; + while(totalCount !== 1) { + let arr = (''+(totalCount || n)).split(''); + totalCount = arr.reduce((total, num) => { + return total + num * num + }, 0) + if (set.has(totalCount)) { + return false; + } + set.add(totalCount); + } + return true; +}; ``` Swift: