happy number

 public static boolean happyNum(int num) {
        if (num < 0) {
            return false;
        }
        int sum = 0;
        while (num > 0) {
            sum += (num % 10) * (num % 10);
            num /= 10;
        }
        if (sum == 1) {
            return true;
        }

        if (sum == 4) {
            return false;
        }

        return happyNum(sum);
    }
def square(x):
    return int(x) * int(x)


def happy(num):
    return sum(map(square, list(str(num))))


def is_happy(num):
    seen_nums = set()
    while num > 1 and (num not in seen_nums):
        seen_nums.add(num)
        num = happy(num)
    return num == 1


print is_happy(19)

 

https://en.wikipedia.org/wiki/Happy_number

 

posted @ 2019-06-04 12:08  java渣渣  阅读(167)  评论(0编辑  收藏  举报