码迷,mamicode.com
首页 > 移动开发 > 详细

happy number

时间:2019-06-04 12:46:53      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:and   app   not   bool   span   als   nbsp   col   int   

 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

 

happy number

标签:and   app   not   bool   span   als   nbsp   col   int   

原文地址:https://www.cnblogs.com/lijiale/p/10972785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!