forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
53 lines (41 loc) · 906 Bytes
/
main.cpp
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
/// Source : https://leetcode.com/problems/happy-number/
/// Author : liuyubobobo
/// Time : 2017-01-18
#include <iostream>
#include <unordered_set>
using namespace std;
/// Using HashTable
/// Time Complexity: O(?)
/// Space Complexity: O(?)
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> record;
record.insert(n);
while(n != 1){
n = op(n);
if( record.find(n) == record.end() )
record.insert(n);
else
return false;
}
return true;
}
private:
int op(int x){
int res = 0;
while(x){
int t = x % 10;
res += t * t;
x /= 10;
}
return res;
}
};
void print_bool(bool res){
cout << (res ? "True" : "False") << endl;
}
int main() {
print_bool(Solution().isHappy(19));
return 0;
}