202. Happy Number

Description

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.

Example: 19 is a happy number


202. Happy Number_第1张图片
image.png

Solution

很有意思的题啊,很纠结如何处理死循环,经点播发现可以使用一个HashSet做辅助,存储遇到过的数字。如果当前数字已经在HashSet中存在了,说明已经陷入死循环,就可以返回false了;

class Solution {
    public boolean isHappy(int n) {
        if (n == 1) return true;
        
        Set inLoop = new HashSet<>();  // nums already met
        while (inLoop.add(n)) { // if already in set, it returns false
            n = sumOfSquares(n);
            if (n == 1) return true;
        }
        
        return false;
    }

    public int sumOfSquares(int n) {
        int sum = 0;
        
        while (n > 0) {
            int digit = n % 10;
            sum += digit * digit;
            n /= 10;
        }
        
        return sum;
    }
}

你可能感兴趣的:(202. Happy Number)