首页 > 移动平台 > 详细

202. Happy Number

时间:2016-07-21 08:39:50      阅读:229      评论:0      收藏:0      [点我收藏+]

写一个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     }

 

202. Happy Number

原文:http://www.cnblogs.com/warmland/p/5690383.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!