這一題比較難的地方是把規則看懂, 以及想辦法把數字拆開來, 簡單運用%和/就可以拆開了, 這會是想得比較久的地方; 本來還想試試看用Recusion的方式來做, 不過似乎是太久沒有寫這玩意.... 我完全腦袋一片空白..; 所以, 如果有人有寫出來的, 也歡迎寫信給我, 讓我知道一下各位的想法囉:D
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 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
Constraints:
1 <= n <= 231 - 1
int cal(int n) {
int x = n;
int s = 0;
while (x > 0) {
s = s + (x % 10)*(x % 10);
x = x / 10;
}
return s;
}
bool isHappy(int n)
{
int x = n;
int y = n;
while (x > 1) {
x = cal(x);
if (x == 1)return true;
y = cal(cal(y));
if (y == 1)return true;
if (x == y)return false;
}
return true;
}
留言列表