Merge pull request #867 from Tiffany-yuan/master

update: 0202.快乐数 js版本 使用Set(),求和用reduce
This commit is contained in:
程序员Carl
2021-10-27 23:22:56 +08:00
committed by GitHub

View File

@ -215,6 +215,23 @@ var isHappy = function(n) {
} }
return n === 1; 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 Swift