美文网首页
202. Happy Number

202. Happy Number

作者: DrunkPian0 | 来源:发表于2017-09-14 00:03 被阅读13次

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
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

我一开始写了递归但不知道怎么处理陷入无限递归的情况,因为我以为会无限不循环,但其实一定会循环的,因为正整数一共就INTEGER.MAX_INT个,所以一定会循环。

用Set做:

public boolean isHappy(int n) {
    Set<Integer> inLoop = new HashSet<Integer>();
    int squareSum,remain;
    while (inLoop.add(n)) {
        squareSum = 0;
        while (n > 0) {
            remain = n%10;
            squareSum += remain*remain;
            n /= 10;
        }
        if (squareSum == 1)
            return true;
        else
            n = squareSum;

    }
    return false;
}

不用Set做:

        public boolean isHappy(int n) {
        if (n <= 0) return false;
        if (n == 1) return true;
        int slow = calc(n);
        int fast = calc(n);
        fast = calc(fast);

        while (slow != fast) {
            slow = calc(slow);
            fast = calc(fast);
            fast = calc(fast);
        }
        return slow == 1;
    }

    private int calc(int n) {
        int sum = 0;
        while (n > 0) {
            int remain = n % 10;
            sum += remain * remain;
            n /= 10;
        }
        return sum;
    }

相关文章

网友评论

      本文标题:202. Happy Number

      本文链接:https://www.haomeiwen.com/subject/xllrsxtx.html