forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhappy-number.cpp
More file actions
27 lines (25 loc) · 570 Bytes
/
happy-number.cpp
File metadata and controls
27 lines (25 loc) · 570 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
// Time: O(k), where k is the steps to be happy number
// Space: O(k)
class Solution {
public:
/**
* @param n an integer
* @return true if this is a happy number or false
*/
bool isHappy(int n) {
unordered_set<int> visited;
while (n != 1 && !visited.count(n)) {
visited.emplace(n);
n = nextNumber(n);
}
return n == 1;
}
int nextNumber(int n) {
int sum = 0;
while (n) {
sum += pow(n % 10, 2);
n /= 10;
}
return sum;
}
};