[leetcode]202.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.

Example:

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

解法一

思路

自己没有做出来,是因为不知道怎么结束循环,看了别人的解法才知道可以用HashSet。用HashSet来保存计算过程中出现过的数字,如果再次出现HashSet中的数字,证明开始循环了,返回false即可。

代码

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<Integer>();
        while(!set.contains(n)) {
            if(n == 1) return true;
            set.add(n);
            n = sumOfSquares(n);
        }
        return false;
        
    }
    
    private int sumOfSquares(int n) {
        int res = 0;
        while(n > 0) {
            int digit = n % 10;
            res += digit * digit;
            n /= 10;
        }
        return res;
    }
}

解法二

思路

还有一种思路和判断单链表中是否有环的思路很像。如果一个数不是happy number,则会出现循环(也即环),那么我们用一快一慢的两个“指针”,慢的每次走一步,快的每次走两步,这样它们终会相遇~当他们相遇时,就说明这个数不是happy number。很精彩的解法,空间复杂度降到O(1)。

代码

class Solution {
    public boolean isHappy(int n) {
        int x = n;
        int y = n;
        while(true) {
            x = sumOfSquares(x);
            if(x == 1) return true;
            y = sumOfSquares(sumOfSquares(y));
            if(y == 1) return true;
            
            if(x == y) return false;
        }
        
    }
    
    private int sumOfSquares(int n) {
        int res = 0;
        while(n > 0) {
            int digit = n % 10;
            res += digit * digit;
            n /= 10;
        }
        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/shinjia/p/9776310.html