[LeetCode] 202. 快乐数

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

    public boolean isHappy(int n) {
        int slow = n, fast = squareSum(n);
        while (slow != fast){
            slow = squareSum(slow);
            fast = squareSum(squareSum(fast));
        };
        return slow == 1;
    }
}

这个想法也太牛了!!我一开始也是想到用递归,考虑到内存可能不狗,没想到这个方法啊。

posted @ 2020-05-01 00:38  doyi  阅读(115)  评论(0编辑  收藏  举报