Leetcode P0202"Happy Number" 题解

2020/10/11 Leetcode

博文中会简要介绍Leetcode P0202题目分析及解题思路。

“Happy Number”这道题比较简单。利用HashTable来存储所有中间出现过的数,从而避免陷入循环。然后每次将数num转化为字符串,对字符串中每个字符遍历来求得下一个数,直到num的值为1或者陷入循环为止。

Write an algorithm to determine if a number n 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.

Return True if n is a happy number, and False if not.

Example:

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

以下是Java的题解代码实现。

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> numSet = new HashSet<>();
        
        while (n != 1 && !numSet.contains(n)) {
            numSet.add(n);
            String num = String.valueOf(n);
            
            n = 0;
            for (int itr=0; itr<num.length(); ++itr) {
                int temp = num.charAt(itr)-'0';
                n += temp*temp;
            }
        }
        
        return (n == 1);
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> num_set;
        
        while (n != 1 && num_set.count(n) == 0) {
            num_set.insert(n);
            string num = to_string(n);
            
            n = 0;
            for (char digit: num) {
                n += (digit-'0')*(digit-'0');
            }
        }
        
        return (n == 1);
    }
};

Search

    Table of Contents