-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path202. Happy Number.js
70 lines (61 loc) · 1.29 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* Note:
* 1. Seperate getNextNumber and isHappy while loop
*/
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
let set = new Set();
while (n !== 1) {
if (set.has(n)) {
return false;
}
set.add(n);
n = getNextNumber(n);
}
return true;
};
/**
* @param {integer} n
* @return {integer}
*/
function getNextNumber(n) {
let sum = 0;
while (n !== 0) {
sum += Math.pow(n % 10, 2);
n = Math.floor(n / 10);
}
return sum;
}
/**
* Leetcode Fundamental: Set, Update 1/21/2019
*/
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
// 1. Use sum of each digits as key of the set
// 2. Use while loop keep adding new sum to the set
// 3. If set.has(sum) -> infinite loop, exit while loop, return false
// 4. If sum === 1, return true
let set = new Set();
let sum = calSum(n);
if (sum === 1) return true;
while (!set.has(sum)) {
set.add(sum);
sum = calSum(sum);
if (sum === 1) return true;
}
return false;
};
const calSum = (n) => {
let sum = 0;
while (n / 10 !== 0) { // no more next quotient
sum += (n % 10) * (n % 10);
n = parseInt(n / 10);
}
return sum;
}