-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhappy_number.cpp
More file actions
38 lines (30 loc) · 776 Bytes
/
happy_number.cpp
File metadata and controls
38 lines (30 loc) · 776 Bytes
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
class Solution {
public:
/**
* @param n an integer
* @return true if this is a happy number or false
*/
const int val_map[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};
int getNextHappy(int n) {
int sum = 0;
while (n != 0) {
int bit = n % 10;
n = n / 10;
sum += val_map[bit];
}
return sum;
}
bool isHappy(int n) {
// Write your code here
set<int> m_set;
while (n != 1) {
auto it = m_set.find(n);
if (it != m_set.end()) {
return false;
}
m_set.insert(n);
n = getNextHappy(n);
}
return true;
}
};