[LeetCode] Happy Number

202. Happy Number

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

  • Time : O(n) n is cycle of formula
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool isHappy(int n) {
int slow = n, fast = n;
do {
slow = convert(slow);
fast = convert(convert(fast));
}while(slow != fast);
return slow == 1;
}
int convert(int n) {
int res = 0, tmp;
while(n) {
tmp = n % 10;
res += tmp * tmp;
n /= 10;
}
return res;
}
};
  • Time : O(n) n is cycle of formula
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> v;
v.insert(n);
while(n != 1) {
int nxt = 0;
while(n) {
nxt += (n % 10) * (n % 10);
n /= 10;
}
if(v.count(nxt)) return false;
v.insert(nxt);
n = nxt;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/28/PS/LeetCode/happy-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.