用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;
}
}

posted on 2016-01-10 09:00  爱推理的骑士  阅读(148)  评论(0编辑  收藏  举报