Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit fa24178

Browse files
Merge pull request youngyangyang04#867 from Tiffany-yuan/master
update: 0202.快乐数 js版本 使用Set(),求和用reduce
2 parents 699443e + 5a69916 commit fa24178

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

problems/0202.快乐数.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,23 @@ var isHappy = function(n) {
215215
}
216216
return n === 1;
217217
};
218+
219+
// 方法四:使用Set(),求和用reduce
220+
var isHappy = function(n) {
221+
let set = new Set();
222+
let totalCount;
223+
while(totalCount !== 1) {
224+
let arr = (''+(totalCount || n)).split('');
225+
totalCount = arr.reduce((total, num) => {
226+
return total + num * num
227+
}, 0)
228+
if (set.has(totalCount)) {
229+
return false;
230+
}
231+
set.add(totalCount);
232+
}
233+
return true;
234+
};
218235
```
219236

220237
Swift:

0 commit comments

Comments
 (0)