202. Happy Number

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> visited;
        while (visited.find(n) == visited.end()) {
            visited.insert(n);
            n = squareSum(n);
        }
        if (n == 1) return true;
        return false;
    }
private:
    int squareSum(int n) {
        int res = 0;
        while (n) {
            res += (n % 10) * (n % 10);
            n /= 10;
        }
        return res;
    }
};
class Solution {
public:
    bool isHappy(int n) {
        int hare = n;
        int tortoise = n;
        do {
            hare = squareSum(squareSum(hare));
            tortoise = squareSum(tortoise);
        } while(hare != tortoise);
        if (hare == 1) return true;
        return false;
    }
private:
    int squareSum(int n) {
        int res = 0;
        while (n) {
            res += (n % 10) * (n % 10);
            n /= 10;
        }
        return res;
    }
};

https://en.wikipedia.org/wiki/Happy\_number

results matching ""

    No results matching ""