編寫(xiě)一個(gè)算法來(lái)判斷一個(gè)數(shù) n 是不是快樂(lè)數(shù)。
「快樂(lè)數(shù)」定義為:對(duì)于一個(gè)正整數(shù),每一次將該數(shù)替換為它每個(gè)位置上的數(shù)字的平方和,然后重復(fù)這個(gè)過(guò)程直到這個(gè)數(shù)變?yōu)?1,也可能是 無(wú)限循環(huán) 但始終變不到 1。如果 可以變?yōu)? 1,那么這個(gè)數(shù)就是快樂(lè)數(shù)。
如果 n 是快樂(lè)數(shù)就返回 True ;不是,則返回 False 。
示例:
輸入:19
輸出:true
解釋:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/happy-number
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
public boolean isHappy(int n) {
int slow = n;
int fast = getSquareNext(n); //循環(huán) 快慢指針 總有相遇的一天
while (fast != 1 && fast != slow) {
slow = getSquareNext(slow);
fast = getSquareNext(getSquareNext(fast));
}
return fast == 1;
}
// 計(jì)算 19=1*1+9*9=82
public int getSquareNext(int n) {
int sum = 0;
while (n > 0) {
int remainder = n % 10;
n = n / 10;
sum += remainder * remainder;
}
return sum;
}