202. Happy Number

写一个digitSum的辅助函数,设一个曾经出现过的set,如果digit sum之后的数是曾经出现过的,就说明会出现循环,不会变成1,退出,返回false,否则循环

辅助函数和今天的reverse Integer一种操作方法,最后一位数字是n % 10, n更新为n/10,退出条件是n != 0

 1     public boolean isHappy(int n) {
 2         Set<Integer> seen = new HashSet<Integer>();
 3         int sum = sumDigits(n);
 4         while(!seen.contains(sum)) {
 5             if(sum == 1) {
 6                 return true;
 7             }
 8             seen.add(sum);
 9             sum = sumDigits(sum);
10         }
11         return false;
12     }
13     
14     private int sumDigits(int n) {
15         int res = 0;
16         while(n != 0) {
17             res += Math.pow((n % 10), 2);
18             n /= 10;
19         }
20         return res;
21     }

 

posted @ 2016-07-21 08:00  warmland  阅读(139)  评论(0编辑  收藏  举报