update: 0202.快乐数 js版本 使用Set(),求和用reduce

This commit is contained in:
mengyuan
2021-10-22 17:26:47 +08:00
parent 6e7f13cb80
commit 5a69916e0f

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