-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0202.happy-number.cpp
More file actions
39 lines (30 loc) · 835 Bytes
/
0202.happy-number.cpp
File metadata and controls
39 lines (30 loc) · 835 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
39
// https://leetcode.com/problems/happy-number/
// this submission is accepted
// but the top answer use vastly more efficient approach
// using hare and tortoise
class Solution {
public:
bool isHappy(int n) {
std::vector<int> tracker;
return recIsHappy(n, tracker);
}
private:
bool recIsHappy(int n, std::vector<int>& tracker) {
if (n == 1) return true;
if (std::find(tracker.begin(), tracker.end(), n) != tracker.end()) {
return false;
}
int num = sumOfDigitSquares(n);
tracker.push_back(n);
return recIsHappy(num, tracker);
}
int sumOfDigitSquares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
};