首页 > 移动平台 > 详细

Jan 09 - Happy Number;loop; digits; Integer;

时间:2016-01-10 09:18:45      阅读:251      评论:0      收藏:0      [点我收藏+]

用hashMap查重:

代码:

public class Solution {
public boolean isHappy(int n) {
Map<Integer, Integer> map = new HashMap<>();
while(!map.containsKey(n)){
map.put(n,1);
int result = 0;
result += (n%10) * (n%10);
while(n/10 > 0){
n /= 10;
result += (n%10) * (n%10);
}
n = result;
}
if(n == 1) return true;
else return false;
}
}

 

不用hashMap:

public class Solution {
public boolean isHappy(int n) {
//Map<Integer, Integer> map = new HashMap<>();
int[] integers = new int[1000];
while(n != 1){
n = getSum(n);
integers[n]++;
if(integers[n] > 1) return false;

}
return true;
}

public int getSum(int n){
int result = 0;
result += (n%10) * (n%10);
while((n = n/10) > 0){
result += (n%10) * (n%10);
}
return result;
}
}

Jan 09 - Happy Number;loop; digits; Integer;

原文:http://www.cnblogs.com/5683yue/p/5117789.html

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