happy number

Posted lijiale

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于happy number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Happy Number

202. Happy Number

LeetCode-Happy Number

[LeetCode][JavaScript]Happy Number

40. leetcode 202. Happy Number

leetCode(29):Happy Number