题目:
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.
解答:
思路:
- 通过
while(n!=0)
循环计算该数字平方计算后的结果,如果计算后结果为1,则说明为happy number - 用set记录每次对一个数进行平方计算后的数,然后每记录一次,都用
while(!set.contains(n))
判断此数是否存在过,如果出现过则说明不是happy number
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> set=new HashSet<>();
int sum=0;
while(!set.contains(n)){
set.add(n);
while(n!=0){
sum+=(n%10)*(n%10);
n=n/10;
}
if(sum==1){
return true;
}
n=sum;
sum=0;
}
return false;
}
}