Skip to content

Commit

Permalink
补充 0202 快乐数 JavaScript版本使用Set() 的解法
Browse files Browse the repository at this point in the history
  • Loading branch information
Jerry-306 authored Sep 25, 2021
1 parent 0f0bb6e commit 59eff2e
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions problems/0202.快乐数.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,30 @@ var isHappy = function(n) {
}
return b === 1 || getN(b) === 1 ;
};

// 方法三:使用Set()更简洁
/**
* @param {number} n
* @return {boolean}
*/

var getSum = function (n) {
let sum = 0;
while (n) {
sum += (n % 10) ** 2;
n = Math.floor(n/10);
}
return sum;
}
var isHappy = function(n) {
let set = new Set(); // Set() 里的数是惟一的
// 如果在循环中某个值重复出现,说明此时陷入死循环,也就说明这个值不是快乐数
while (n !== 1 && !set.has(n)) {
set.add(n);
n = getSum(n);
}
return n === 1;
};
```

Swift:
Expand Down

0 comments on commit 59eff2e

Please sign in to comment.