-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.cpp
46 lines (42 loc) · 880 Bytes
/
Solution.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
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <deque>
#include <unordered_map>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
// this is a two pointer method
class Solution {
public:
int next(int n) {
int sum = 0;
while (n != 0) {
int d = n % 10;
n /= 10;
sum += d * d;
}
return sum;
}
// two pointer
bool isHappy(int n) {
if (n <= 0) return false;
int slow = next(n);
int fast = next(slow);
while (true) {
if (fast == slow) break;
slow = next(slow);
fast = next(next(fast));
if (fast == 1) return true;
}
return fast == 1 ? true : false;
}
};
int main() {
Solution a;
return 0;
}