-
Notifications
You must be signed in to change notification settings - Fork 0
/
0202.HappyNumber.js
114 lines (80 loc) · 2.11 KB
/
0202.HappyNumber.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Write an algorithm to determine if a number n is happy.
// A happy number is a number defined by the following process:
// Starting with any positive integer, replace the number by the sum of the squares of its digits.
// Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
// Those numbers for which this process ends in 1 are happy.
// Return true if n is a happy number, and false if not.
//
// Example 1:
// Input: n = 19
// Output: true
// Explanation:
// 12 + 92 = 82
// 82 + 22 = 68
// 62 + 82 = 100
// 12 + 02 + 02 = 1
// Example 2:
// Input: n = 2
// Output: false
//
// Constraints:
// 1 <= n <= 231 - 1
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/happy-number
// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 🎨 方法一:hash
// 📝 思路:用set判断是否出现重复元素来判断循环环的首个元素
//
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function (n) {
let set = new Set();
while (n !== 1) {
let c = squareSum(n);
if (set.has(c)) {
return false
}
set.add(c)
n = c;
}
return true
};
function squareSum(num) {
let res = 0;
while (num) {
let l = num % 10;
num = parseInt(num / 10);
res += l ** 2
}
return res
}
// 🎨 方法一:快慢指针
// 📝 思路:其实是隐式的链表,可以用快慢指针判断是否成环
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function (n) {
let slow = squareSum(n);
let fast = squareSum(squareSum(n));
while (slow !== 1 && fast !== 1) {
if (slow === fast) {
return false;
}
slow = squareSum(slow);
fast = squareSum(squareSum(fast));
}
return true;
};
function squareSum(n) {
let sum = 0;
let newNum = n;
while (newNum) {
let last = newNum % 10;
newNum = parseInt(newNum / 10);
sum += last ** 2;
}
return sum;
}