一直求数每个位的平方和,算出来再继续上一步操作,算到等于1的话就是开心数
描述
Input: 19
Output: true
Explanation:
11 + 99 = 82
88 + 22 = 68
66 + 88 = 100
11+ 00 + 0*0 = 1
我们这里主要是找到如何破除循环,即使他不是开心数的时候
下面是java代码,我们使用快慢数去存储
public class Solution {
public boolean isHappy(int n) {
int slow = n,fast = n;
//第一次是肯定相等的
do
{
slow = caculateHappy(slow);
fast = caculateHappy(fast);
//前两次是一样的,第三次就向前快走了一步
fast = caculateHappy(fast);
}while(slow != fast);
if (slow == 1) return true;
else return false;
}
public int caculateHappy(int n){
int tmp,res = 0;
while(n!=0){
//用10的余数取到最后一位个数
tmp = n%10;
res += tmp*tmp;
//把最后一位去除掉,因为他已经没有价值了
n /= 10;
}
return res;
}
}