题目要求:求一个正整数的所有数字的平方和,若能得到1,则为happy number ,反之不为happy number。
tags:hashtable,math,two pointers
我的思路:
1.首先计算该数字的平方和,将所有的平方和存入HashSet中,
2.如果平方和为1,则返回true,
3.如果HashSet中有相同的元素,则返回false,
public int square(int n){
int temp = 0;
while(n!=0){
temp = temp + (int)Math.pow(n%10,2);
n=n/10;
}
return temp;
}
public boolean isHappy2(int n){
HashSet<Integer> set = new HashSet<Integer>();
while(true){
if(n==1){
return true;
}else if(set.contains(n)){
return false;
}else{
set.add(n);
n=square(n);
}
}
}
别人的思路:使用快慢指针
1.建两个指针,fast指向循环次数多的平方和,slow指向循环次数少的平方和,
2.其中fast每次循环计算两次平方和,slow每次循环计算1次平方和,
3.如果有重复,那么快慢指针指向的数字则相同,如果快指针指向1(快指针肯定比慢指针要快到达1),则说明为happy number。
public boolean isHappy(int n) {
int fast = n;
int low = n;
while(true){
fast = square(square(fast));
low = square(low);
if(fast==1){
return true;
}else if(fast==low){
return false;
}
}
}