-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhappy-number.js
62 lines (54 loc) · 1.09 KB
/
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
53
54
55
56
57
58
59
60
61
62
/**
* @param {number} n
* @return {boolean}
*/
// Solution 1
var isHappy = function (n) {
if (n === 1 || n === 7) {
return true;
}
if (n < 10) {
return false;
}
var marked = [];
var arr = n.toString().split('');
var ret = 0;
for (var i = 0; i < arr.length; i++) {
ret += parseInt(arr[i]) * parseInt(arr[i]);
}
if (ret === 1) {
return true;
} else {
if (marked.includes(ret)) {
return false;
} else {
marked.push(ret);
return isHappy(ret);
}
}
};
// Solution 2
/**
* @param {number} n
* @return {boolean}
*/
function isHappyHelper(n, hash) {
var arr = n.toString().split('');
var ret = 0;
for (var i in arr) {
ret += parseInt(arr[i]) * parseInt(arr[i]);
}
if (ret === 1) {
return true;
} else {
if (hash.includes(ret)) {
return false;
} else {
hash.push(ret);
return isHappyHelper(ret, hash);
}
}
}
var isHappy = function (n) {
return isHappyHelper(n, []);
};