LeetCode p202 Happy Number 题解
1.题目:
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 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
题意:
判断一个数是否为快乐数,即在按如上规律运算时,最后会得到1.如果不是快乐数,则会得到一个循环。
2.解题思路:
见代码。。先找出了那个循环中的某个数。。然后进行比对,在为1之前陷入循环的话则不是快乐数。
3.代码
1 |
|