LeetCode之Happy Number

/*用一個Hash表記錄出現過得數字。採用如下步驟獲得結果:
從當前正數n開始,1)如果n == 1,則它爲happy number,返回true,結束。
2)如果n != 1, 且hash表中有等於n的數字,會陷入循環,返回false,結束。
3)如果n != 1,且hash表中沒有等於n的數字,則將n加入hash表,繼續計算下一個n。重複。*/
class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> appeared;
        while(n != 1){
            n = replace(n);
            if(appeared.find(n) != appeared.end()) return false;
            else appeared.insert(n);
        }
        return true;
    }
    
    int replace(int n){
        int res = 0; 
        while(n > 0){
            int tmp = n%10;
            res = res + tmp * tmp;
            n /= 10;
        }
        return res;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章