LeetCode 202. Happy Number

判断是否有循环的问题。

解法一:可以用hash表将出现过的值保存起来,再次出现即说明有循环。

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> s;
        while (true){
            if (n==1) return true;
            if (s.count(n)) return false;
            else s.insert(n);
            n = square_sum(n);
        }
    }
    
    int square_sum(int n){
        int sum=0;
        while (n){
            sum += pow(n%10,2);
            n /= 10;
        }
        return sum;
    }
};

解法二:应用Floyd Cycle Detection算法,设一个快变量一个慢变量。如果循环存在,它们一定会相遇。

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> s;
        int slow, fast;
        slow = fast = n;
        do{
            slow = square_sum(slow);
            fast = square_sum(square_sum(fast));
        }while(slow!=fast);
        if (slow==1) return true;
        else return false;
    }
    
    int square_sum(int n){
        int sum=0;
        while (n){
            sum += pow(n%10,2);
            n /= 10;
        }
        return sum;
    }
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9125771.html