p202

LeetCode p202 Happy Number 题解

1.题目:

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: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

题意:

判断一个数是否为快乐数,即在按如上规律运算时,最后会得到1.如果不是快乐数,则会得到一个循环。

2.解题思路:

见代码。。先找出了那个循环中的某个数。。然后进行比对,在为1之前陷入循环的话则不是快乐数。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
public class Solution {
public boolean isHappy(int n) {
while (n != 1 && n != 4) {
int s = 0;
while (n != 0) {
s += (n % 10) * (n % 10);
n = n / 10;
}
n = s;
s = 0;
}
return 1 == n;
}
}


4.一些总结: