LeetCode Solutions

202. Happy Number

Time: $O(\log n)$

Space: $O(1)$

			

class Solution {
 public:
  bool isHappy(int n) {
    int slow = squaredSum(n);
    int fast = squaredSum(squaredSum(n));

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

    return slow == 1;
  }

 private:
  int squaredSum(int n) {
    int sum = 0;
    while (n) {
      sum += pow(n % 10, 2);
      n /= 10;
    }
    return sum;
  };
};
			

class Solution {
  public boolean isHappy(int n) {
    int slow = squaredSum(n);
    int fast = squaredSum(squaredSum(n));

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

    return slow == 1;
  }

  private int squaredSum(int n) {
    int sum = 0;
    while (n > 0) {
      sum += Math.pow(n % 10, 2);
      n /= 10;
    }
    return sum;
  }
}
			

class Solution:
  def isHappy(self, n: int) -> bool:
    def squaredSum(n: int) -> bool:
      summ = 0
      while n:
        summ += pow(n % 10, 2)
        n //= 10
      return summ

    slow = squaredSum(n)
    fast = squaredSum(squaredSum(n))

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

    return slow == 1