202. Happy Number Leetcode Python

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+ 02+ 02= 1

Credits:Special thanks to@mithmattand@tsfor adding this problem and creating all test cases.

This algorithm need to validate its digits.

class Solution:# @param {integer} n# @return {boolean}def isHappy(self, n):val = set()while n not in val:val.add(n)newn = 0while n != 0:newn += (n % 10) * (n % 10)n /= 10n = newnif n == 1:return Truereturn False

,每一个成功者都有一个开始。勇于开始,才能找到成功的路。

202. Happy Number Leetcode Python

相关文章:

你感兴趣的文章:

标签云: