[202] leetcode happy number (hash table)

Topic links: https://leetcode-cn.com/problems/happy-number/

Title Description

Write an algorithm to determine if a number is not "count his joys."

A "happy number" is defined as: For a positive integer, each time replacing the squared number of its digits at each position and then repeat the process until the number becomes 1, it may be variable but has an infinite loop less than 1. If you can become one, then this number is the happy number.

Example:

输入: 19
输出: true
解释: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Thinking

Digital memory hash table has appeared, if the next combination is already present in the table, then into an infinite loop.

Code

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> s;   // 记录已经出现的组合
        n = digitSquareSum(n);
        while (n!=1){
            if(s.find(n) != s.end())    // 出现循环
                return false;
            s.insert(n);
            n = digitSquareSum(n);
        }
        return true;
    }

private:
    int digitSquareSum(int n){
        int ret = 0;
        while (n>0){
            ret += (n % 10) * (n % 10);
            n /= 10;
        }
        return ret;
    }
};

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/zjwreal/article/details/94559268