-
Notifications
You must be signed in to change notification settings - Fork 0
/
happy_number.cpp
54 lines (51 loc) · 1.16 KB
/
happy_number.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
54
/*
* =====================================================================================
*
* Filename: happy_number.cpp
*
* Description: 202. Happy Number https://leetcode.com/problems/happy-number/
*
* Version: 1.0
* Created: 02/22/2022 15:29:18
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <cstdio>
#include <cstdlib>
#include <unordered_set>
class Solution {
public:
bool isHappy(int n) {
auto replace = [](int n) -> int {
int sum = 0;
while (n != 0) {
sum += std::pow(static_cast<double>(n % 10), 2.0);
n /= 10;
}
return sum;
};
std::unordered_set<int> nums;
while (true) {
nums.insert(n);
n = replace(n);
if (nums.count(n) > 0) {
break;
}
}
return (n == 1);
}
};
int main(int argc, char* argv[]) {
int n = 19;
if (argc > 1) {
n = std::atoi(argv[1]);
}
printf("n = %d\n", n);
printf("%s\n", (Solution().isHappy(n) ? "true" : "false"));
return 0;
}