题目
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
十分钟尝试
我的尝试思路,以前处理过int类型数据如何求出每一位,对,就是求mod运算,然后平方相加就可以。代码如下:
class Solution {
public boolean isHappy(int n) {
int res=0;
while(true){
while(n>0){
int mod=n%10;
res+=Math.pow(mod,2);
n=n/10;
}
if(res==1){
return true;
}
n=res;
}
return false;
}
}
问题是无限循环,leetcode测试不通过。题目也说的是loop endlessly。不知道这个地方如何处理。看了他人对答案,用set.存储当前的和,如果能add,继续。另外,上面的代码有个问题,res应该在第一个while循环里面,修改如下,完美通过;
class Solution {
public boolean isHappy(int n) {
Set<Integer> set=new HashSet();
while(set.add(n)){
int res=0;
while(n>0){
int mod=n%10;
res+=Math.pow(mod,2);
n=n/10;
}
if(res==1){
return true;
}
n=res;
}
return false;
}
}