1. 程式人生 > 其它 >[LeetCode] #202 快樂數

[LeetCode] #202 快樂數

[LeetCode] #202 快樂數

編寫一個演算法來判斷一個數 n 是不是快樂數。

「快樂數」定義為:

對於一個正整數,每一次將該數替換為它每個位置上的數字的平方和。
然後重複這個過程直到這個數變為 1,也可能是 無限迴圈 但始終變不到 1。
如果 可以變為 1,那麼這個數就是快樂數。

如果 n 是快樂數就返回 true ;不是,則返回 false 。

首先寫一個輔助函式,將該數替換為它每個位置上的數字的平方和

private int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n 
= n / 10; totalSum += d * d; } return totalSum; }

可以遞迴,當結果小於10,但不等於1或7,則會無限迴圈

class Solution {
    public boolean isHappy(int n) {
        if(n == 1 || n == 7) return true;
        else if(n < 10) return false;
        return isHappy(getNext(n));     
    }
    private
int getNext(int n) { int totalSum = 0; while (n > 0) { int d = n % 10; n = n / 10; totalSum += d * d; } return totalSum; } }

使用HashSet,出現1為快樂數,新增重複且不等於1則說明會進入無限迴圈

class Solution {
    private int getNext(int n) {
        int totalSum = 0;
        
while (n > 0) { int d = n % 10; n = n / 10; totalSum += d * d; } return totalSum; } public boolean isHappy(int n) { Set<Integer> seen = new HashSet<>(); while (n != 1 && !seen.contains(n)) { seen.add(n); n = getNext(n); } return n == 1; } }

使用快慢指標,指標相遇說明進入無限迴圈

class Solution {

     public int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }

    public boolean isHappy(int n) {
        int slowRunner = n;
        int fastRunner = getNext(n);
        while (fastRunner != 1 && slowRunner != fastRunner) {
            slowRunner = getNext(slowRunner);
            fastRunner = getNext(getNext(fastRunner));
        }
        return fastRunner == 1;
    }
}

知識點:

總結: