Skip to content

202. Happy Number 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  bool isHappy(int n) {
    auto helper = [&](int n) {
      int sum = 0;
      while (n) {
        sum += pow(n % 10, 2);
        n /= 10;
      }
      return sum;
    };

    int slow = helper(n);
    int fast = helper(helper(n));

    while (slow != fast) {
      slow = helper(slow);
      fast = helper(helper(fast));
    }

    return slow == 1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public boolean isHappy(int n) {
    int slow = helper(n);
    int fast = helper(helper(n));

    while (slow != fast) {
      slow = helper(slow);
      fast = helper(helper(fast));
    }

    return slow == 1;
  }

  private int helper(int n) {
    int sum = 0;
    while (n > 0) {
      sum += Math.pow(n % 10, 2);
      n /= 10;
    }
    return sum;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def isHappy(self, n: int) -> bool:
    def helper(n: int) -> bool:
      sum = 0

      while n:
        sum += pow(n % 10, 2)
        n //= 10

      return sum

    slow = helper(n)
    fast = helper(helper(n))

    while slow != fast:
      slow = helper(slow)
      fast = helper(helper(fast))

    return slow == 1
Back to top