Happy Number
lc 202
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.
所有数字每一个加起来的结果重复进行计算,直到结果变成1或者结果循环为止。
我一开始的做法优点笨,把正数转成了string,然后一位一位的算,这样new了好几个string,其实对于一个整数,利用除以10,余数就是最末尾的数,然后再除10,商就是下一位的数。。思路比较好。
public class Solution {
private int getNextHappy(int n) {
int sum = 0;
while (n != 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
HashSet<Integer> hash = new HashSet<Integer>();
while (n != 1) {
if (hash.contains(n)) {
return false;
}
hash.add(n);
n = getNextHappy(n);
}
return true;
}
}