1問題描述
編寫一個算法來判斷一個數是否爲快樂數
快樂數定義:對於一個正整數,每一次將該數替換爲它每個位置數字的平方和,重複,如果能變到1就是快樂數否則就不是快樂數
//測試:
//輸入19
//運算:
1^2+9^2=82
8^2+2^2=68
6^2+8^2=100
1^2+0^2+0^2=1
//輸出:true
注意的點:
出現環:不是快樂數
package se.SE.practice;
public class HappyNumber {
/**
* @param n an integer
* @return true if this is a happy number or false
*/
public boolean isHappy(int n) {
if(n==1){
return true;
}
if(n<1){
return false;
}
int count=0;
while(n!=1){
String s=n+"";
char []arr=s.toCharArray();
int sum=0;
for(int i=0;i<arr.length;i++){
sum+=Integer.parseInt(arr[i]+"")*Integer.parseInt(arr[i]+"");
}
n=sum;
count++;
if(count>1000){
return false;
}
}
return true;
}
}