Skip to main content

202. Happy Number

Happy Number 的定義 Happy number - Wikipedia

  • HashSet
class Solution {
public:
bool isHappy(int n)
{
unordered_set<int> seen;
while (n != 1 && !seen.count(n))
{
seen.insert(n);
n = getNext(n);
}
return n == 1;
}

int getNext(int n)
{
int totalSum = 0;
while (n > 0)
{
int digit = n % 10;
n = n / 10;
totalSum += digit * digit;
}
return totalSum;
}
};
  • T: O(logn)O(\log n)

  • S: O(logn)O(\log n)

  • Floyd's Cycle-Finding Algorithm

class Solution {
public:
bool isHappy(int n)
{
int slow = n;
int fast = getNext(n);
while (fast != 1 && slow != fast)
{
slow = getNext(slow);
fast = getNext(getNext(fast));
}
return fast == 1;
}

int getNext(int n) {
int totalSum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
totalSum += d * d;
}
return totalSum;
}
};
  • T: O(logn)O(\log n)
  • S: O(1)O(1)