-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path202.cpp
More file actions
36 lines (35 loc) · 1 KB
/
202.cpp
File metadata and controls
36 lines (35 loc) · 1 KB
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
// Author: btjanaka (Bryon Tjanaka)
// Problem: (LeetCode) 202
// Title: Happy Number
// Link: https://leetcode.com/problems/happy-number/
// Idea: Repeatedly compute the sum of square of digits of the numbers. Check if
// the sum has been seen before using a set. There seems to be a way to do this
// that is more mathematical but this method works. Complexity for the sum
// computation is O(log n) (specifically log base 10). Unclear what the maximum
// number of loops is for the numbers, but set check is O(1), so final
// complexity is O(??? log n).
// Difficulty: Easy
// Tags:
class Solution {
public:
int squareDigits(int n) {
int sum = 0;
while (n > 0) {
int x = n % 10;
sum += x * x;
n /= 10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> nums;
nums.insert(n);
while (true) {
int sum = squareDigits(n);
if (sum == 1) return true;
if (nums.find(sum) != nums.end()) return false;
nums.insert(sum);
n = sum;
}
}
};