题目
快乐数字!
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:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
思路1
由题可知,不断对各个位上的数字进行 平方 后 求和的操作,最终会有两种结果:
- 最终结束为1
- 进入无限循环
关键在于如何判断进入了循环? 循环意味着结果重复出现,那么就想到了重复判断类问题,进而想到了使用HashSet这个强大的集合来进行判断,当重复元素被add时会返回false(这个知识点值得牢记啊!),以此来作为进入循环的标志。
此外,依次取一个整数上的所有位数,用经典的循环来实现:先%10取出个位,再/10进行右移。
代码1
class Solution{
public boolean isHappy(int n) {
Set<Integer> inLoop = new HashSet<Integer>();//用来保存所有运算产生的结果,这里面的结果都是不重复的
int squareSum,remain;
while (inLoop.add(n)) {//add返回为true则继续循环语句,因为还未进入“循环”状态
squareSum = 0;//用来保存平方后的和
while (n > 0) {
remain = n%10;//取个位
squareSum += remain*remain;//平方后加入结果
n /= 10;//右移一位
}
if (squareSum == 1)
return true;//happy ending ,直接返回
else
n = squareSum;//替换掉原来的数字继续下一次求和
}
return false;//退出while语句说明进入了循环
}
}
提交结果
Runtime: 1 ms, faster than 89.66% of Java online submissions for Happy Number.
Memory Usage: 35.2 MB, less than 14.28% of Java online submissions for Happy Number.
思路2
还有一种更快的方法,不需要再检测重复。怎么回事呢?
这基于试验后的结论:任何数字经过一定次数的“求各位平方之和”后,都会得到1位数的结果。
其中“1”和“7”不会在后面的运算中进入循环,因为7->49->94->130->10->1最终将终结于1。
而其余的1位数字(比如2,3,4等等)在继续求和的过程中将进入循环。
那么我们只需要在求和结果为个位数时进行判断即可。
当然,这需要对数字的特征进行一定的分析后才能发现,并且,我自己也无法解释为什么唯独“7”不会循环而其它数字会产生,这样一来就有了投机取巧的嫌疑,当然,效率上是比上一种解法快的,但是上面的解法更通用也更加明了。
代码2(递归)
class Solution{
public boolean isHappy(int n) {
if(n<10) {//个位数则判断
if(n==1||n==7) return true;
else return false;
}
int b;int sum=0;
while(n>0) {
b=n%10;
sum=sum+b*b;
n=n/10;
}
return isHappy(sum);//递归求平方和
}
}
提交结果
Runtime: 0 ms, faster than 100.00% of Java online submissions for Happy Number.
Memory Usage: 34.8 MB, less than 83.74% of Java online submissions for Happy Number.
代码3(同思路2的非递归写法)
class Solution{
public boolean isHappy(int n) {
int b;int sum=0;
while(n >= 10){
sum = 0 ;
while(n>0) {
b=n%10;
sum=sum+b*b;
n=n/10;
}
n = sum;
}
if(n==1||n==7)
return true;
else
return false;
}
}
提交结果
Runtime: 0 ms, faster than 100.00% of Java online submissions for Happy Number.
Memory Usage: 34.9 MB, less than 73.19% of Java online submissions for Happy Number.