Description:
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.
Note:
Example: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
Solution:
Analysis and Thinking:
題目要求循環計算每位數字的平方和,知道出現結果爲1時返回True,或者重複返回False
Steps:
1.定義平方和輔助函數,獲得其模10以及除10的結果,將其相乘與前一記錄和值相加,直到n除10結果爲0
2.定義map用於記錄過程,計算輸入數字餓平方和
3.當平方和不爲1,查找在record對應下標是否爲true,若是,重複了,返回false
4.若不是,置其爲true
5.最後表示沒有重複,且到了平方和爲1,返回true
Codes:
class Solution {
public:
bool isHappyNum(int x) {
unordered_map<int, bool> record;
int sum = helper_Sum(x);
while(sum != 1)
{
if(record[sum] == true)
return false;
record[sum] = true;
sum = helper_Sum(sum);
}
return true;
}
int helper_Sum(int n)
{
int result = 0;
while(n)
{
int temp = n%10;
n /= 10;
result = result+(temp*digit);
}
return result;
}
};
Results: