ACM题库~

LeetCode 202. Happy Number

2017-09-30  本文已影响14人  关玮琳linSir

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

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

题意:
给一个数字,区分成每一位,分别平方,求和,相加,判断是否为1,如果为1则停止,否则继续判断。

思路:
每一步都很简单,稍微复杂一点的也就是,什么之后把循环停下来,停下循环的条件就是,当我们发现数字重复的时候,就可以停止循环了。

java代码:

public boolean isHappy(int n) {
        if (n == 0) return false;
        if (n == 1) return true;
        return number(n);
    }

    public boolean number(int n) {
        int count = n;
        HashSet<Integer> set = new HashSet<Integer>();
        while (set.add(count)) {
            int a = 0;
            while (count > 0) {
                int num = count % 10;
                a += num * num;
                count = count / 10;
            }
            if (a == 1) {
                return true;
            } else {
                count = a;
            }
        }
        return false;
    }
上一篇下一篇

猜你喜欢

热点阅读