202. Happy Number

1. Description

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.

2. Example

Example 1:
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1 Example 2:
Input: n = 2
Output: false

3. Constraints

  • 1 <= n <= $2^{31} - 1$

4. Solutions

Hash Table

Time complexity: O(logn)
Space complexity: O(logn)

class Solution {
public:
    bool isHappy(const int n) {
        unordered_map<int, bool> num_occur;
        for (int sum = n; sum != 1; ) {
            int next_sum = 0;
            while (sum > 0) {
                int digit = sum % 10;
                next_sum += digit * digit;
                sum /= 10;
            }

            sum = next_sum;
            if (num_occur[sum]) {
                return false;
            }

            num_occur[sum] = true;
        } 

        return true;
    }
};

Two Pointers

Time complexity: O(logn)
Space complexity: O(logn)

class Solution {
public:
    bool isHappy(int n) {
        int slow_number = n;
        int fast_number = get_next_number_(n);

        while (fast_number != 1 && slow_number != fast_number) {
            slow_number = get_next_number_(slow_number);
            fast_number = get_next_number_(get_next_number_(fast_number));
        }

        return fast_number == 1;
    }

private:
    int get_next_number_(int n) {
        int digit_sum = 0;
        for (; n > 0; n /= 10) {
            int digit = n % 10;
            digit_sum += digit * digit;
        }

        return digit_sum;
    }
};
comments powered by Disqus