1. 程式人生 > >Leetcode刷題記錄——202. Happy Number

Leetcode刷題記錄——202. Happy Number

  • 題目

Write an algorithm to determine if a number 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, and 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 numbers.

Example:

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
  • 題目大意

給你一個整數,讓你判斷這個數是不是“happy”, happy數的定義是說,如果一個數將其每一位數的平方和再繼續運算直到最後為1,則為happy數,如果中間其平方和出現相同的數字迴圈,則不為happy數。

  • 解題思路

主體是將一個整數,求其每個位數的平方加起來的和,這個數再按這種規則繼續運算下去,直至出現1或者出現之前已經求過的和,即產生迴圈,所以需要一個hash來儲存每一次求得的平方和。

bool isHappy(int n) {
    unordered_set<int> old_integer;    /*儲存歷史平方和*/

    while( old_integer.find(n) == old_integer.end() )    /*如果歷史未遇到n*/
    {    

        old_integer.insert(n);
        int sum = 0;

        while( n > 0 )
        {
            int d = n % 10;
            sum += d * d;
            n = n / 10; 
        }

        n = sum;        /*將求得的平方和作為n*/
    }
    return n == 1;
    
}