Happy Number

题目:

Write an algorithm to determine if a number is happy.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

分析:

题目读读好,就是说停在1的是happy,而循环的是not happy。

解法:

class Solution {
public:
    /**
     * @param n an integer
     * @return true if this is a happy number or false
     */
    bool isHappy(int n) {
        // Write your code here
        if (n <= 0) {
            return false;
        } 

        int newTarget = n;
        unordered_set<int> Hash;
        while (1) {
            int sum = 0;
            while (newTarget != 0) {
                int digit = newTarget % 10;
                newTarget /= 10;
                sum += digit * digit;
            }

            if (sum == 1) {
                return true;
            }

            if (Hash.find(sum) == Hash.end() ) {
                Hash.insert(sum);
                newTarget = sum;
            } else {
                return false;
            }
        }

    }
};

results matching ""

    No results matching ""