題目要求:求一個正整數的所有數字的平方和,若能得到1,則爲happy number ,反之不爲happy number。
tags:hashtable,math,two pointer
我的思路:
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;
}
}
}