編寫一個算法來判斷一個數(shù)是不是“快樂數(shù)”席吴。
一個“快樂數(shù)”定義為:對于一個正整數(shù),每一次將該數(shù)替換為它每個位置上的數(shù)字的平方和捞蛋,然后重復這個過程直到這個數(shù)變?yōu)?1孝冒,也可能是無限循環(huán)但始終變不到 1。如果可以變?yōu)?1拟杉,那么這個數(shù)就是快樂數(shù)庄涡。
示例:
輸入: 19
輸出: true
解釋:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
解
采用快慢指針的思想,如果一個數(shù)不是快樂數(shù)搬设,那么必然成為一個不包含1的環(huán)穴店,判斷快指針追上慢指針值時的數(shù)值,如果為1則是快樂數(shù)拿穴,如果不為1泣洞,那么不是快樂數(shù)。
public static boolean isHappy(int n) {
int slow = n;
int fast = n;
do {
slow = calu(slow);
fast = calu(fast);
fast = calu(fast);
}while(slow!=fast);
if(1==fast)
return true;
return false;
}
public static int calu(int n) {
int res = 0;
while(n>0) {
res = res + (n%10) * (n%10);
n = n/10;
}
return res;
}