Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Happy Number - Solution/C++

202. Happy Number

Question:

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.

Example:

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

Input: n = 2
Output: false

Constraints:
  • 1 <= n <= 2^31 - 1
  • Source code

    Version 1

    Idea:
    At first, I suggest you realizing what is unhappy number? You will find out the rule. E.g., n = 48
    42 + 82 = 80
    82 + 02 = 64
    62 + 42 = 52
    52 + 22 = 29
    22 + 92 = 85
    82 + 52 = 89
    82 + 92 = 145
    12 + 42 + 52 = 42
    42 + 22 = 20
    22 + 02 = 4
    42 = 16
    12 + 62 = 37
    32 + 72 = 58
    52 + 82 = 89

    From the above example, you can find the regular process. If a number is unhappy number, the output will repeat. (In this case, 89 is repeated number)

    Hence, you can take the unordered_map container to store each output.
    Then, use count() to check whether the output exists in container or not, if it has already existed, count() will return false, and it means a number is unhappy number. On the contrary, if the ouput is 1, break the while() and return true.

    Time complexity: O(log(n))
    Space complexity: O(n)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    class Solution {
    public:
    bool isHappy(int n) {
    unordered_map<int, int> umap;
    while(n != 1){
    int sum = 0;
    while(n != 0){
    sum += pow(n%10, 2);
    n /= 10;
    }
    if(umap.count(sum)) return false;
    umap.insert(pair<int,int>(sum, sum));
    n = sum;
    }
    return true;
    }
    };

    Version 2

    Idea:
    We can also adopt Floyd's Cycle Finding Algorithm, the program will stop at the same number. Then, if this number is 1, return true. Otherwise, return false.

    Time complexity: O(log(n))
    Space complexity: 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) {
    int slow = n;
    int fast = n;
    do{
    slow = nextvalue(slow);
    fast = nextvalue(fast);
    fast = nextvalue(fast);
    }while(slow != fast);
    if(slow == 1) return true;
    return false;
    }
    private:
    int nextvalue(int n){
    int sum = 0;
    while(n){
    sum += pow(n%10, 2);
    n /= 10;
    }
    return sum;
    }
    };