LeetCode OJ 202. Happy Number

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 + 9= 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

happy number是把一个数的各个位置的数字的平方相加,直到值为1为止。如果一个数是happy number,那么最终的结果一定会是1,如果不是,这个过程将一直持续下去,并且会重复出现以前曾经出现过的数。例如2。

22 = 4

42 = 16

12 + 62 = 37

32 + 72 = 58

52 + 82 = 89

82 + 92 = 145

12 + 42 + 52 = 42

42 + 22 = 20

22 + 02 = 4

···

所以2不是一个happy number。我们的思路就是记录这个过程中出现过的每一个数,如果某些数字在过程中重复出现,则该数肯定不是happy number。如果最后结果是1,则该数是happy number。代码如下:

 1 public class Solution {
 2     public boolean isHappy(int n) {
 3         List<Integer> list = new ArrayList<>();
 4         while (n != 1) {
 5             if (list.contains(n)) {
 6                 return false;
 7             }
 8             list.add(n);
 9             n = toArrayAndSum(n);
10         }
11         return true;
12     }
13     
14     public static int toArrayAndSum(int n) {
15         int sum = 0;
16         while (n > 0) {
17             int x = n % 10;
18             n = n / 10;
19             sum = sum + x * x;
20         }
21             return sum;
22     }
23 }

 

posted @ 2016-04-12 15:34  Black_Knight  阅读(220)  评论(0编辑  收藏  举报