-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path202.happy-number.js
52 lines (49 loc) · 946 Bytes
/
202.happy-number.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* @lc app=leetcode id=202 lang=javascript
*
* [202] Happy Number
*/
// @lc code=start
/**
* @param {number} n
* @return {boolean}
*/
// var isHappy = function(n) {
// let memo = new Set()
// let nStr = n.toString()
// while (n !== 1) {
// let sum = 0
// for (let i = 0; i < nStr.length; i++) {
// sum = sum + Math.pow(Number(nStr[i]), 2)
// }
// if (memo.has(sum)) return false
// else {
// memo.add(sum)
// n = sum
// nStr = sum.toString()
// sum = 0
// }
// }
// return true
// }
var isHappy = function(n) {
let memo = new Set()
while (n !== 1) {
n = n
.toString()
.split('')
.map(digit => {
return parseInt(digit, 10)
})
.reduce((total, digit) => {
return total + digit * digit
}, 0)
if (memo.has(n)) return false
else memo.add(n)
}
return true
}
// @lc code=end
module.exports = {
isHappy
}