由於題目要求是最短時間實現,不要考慮實現本身的效率
1
如果直接去實現,就是比較數字的最高位值和最低位,然後再。。
public boolean isP(int x){
int bit = 1;
int temp = 10;
while(x>temp){bit++;temp*=10;}
if(x==temp)bit++;
// bit爲數值位數
int temp1, temp2;
for(int i=0;i<bit/2;i++){
temp = (int)Math.pow(10,i);
temp1 = x%(temp*10)/temp;
temp = (int)Math.pow(10,bit-i-1);
temp2 = x%(temp*10)/temp;
if(temp1==temp2)continue;
else return false;
}
return true;
}
這個方法是數值比較,實現時很容易出錯,實現時間比較長,其實效率也不高
2
換一種思路,把數值轉爲char[],再比較,
public boolean isP(int x){
char[] temp = (""+x).toCharArray();
for(int i=0; i<temp.length/2; i++){
if(temp[i]!=temp[temp.length-i-1])
return false;
}
return true;
}
雖然都很簡單,但是僅以此文告誡自己動手寫代碼之前要三思