生活随笔
收集整理的這篇文章主要介紹了
力扣09-回文数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
第一種解法,是將整數(shù)轉(zhuǎn)換為字符串,排除x<0這種必不為回文數(shù)的情況,和x=0這種必為回文數(shù)的情況,x>0的情況以字符串中間位置為界,循環(huán)判斷兩側(cè)字符是否相等。
import java
.util
.Scanner
;public class Palindrome9 {public static void main(String
[] args
) {System
.out
.println("請(qǐng)輸入一個(gè)整數(shù)");Scanner sc
= new Scanner(System
.in
);int x
= sc
.nextInt();System
.out
.println(isPalindrome(x
));}public static boolean isPalindrome(int x
) {if(x
<0){return false;}if(x
==0){return true;}String str
= String
.valueOf(x
);int len
=str
.length();for (int i
= 0; i
< len
/2; i
++) {if(str
.getBytes()[i
]!=str
.getBytes()[len
-i
-1]){return false;}}return true;}
}
第二種解法,不將整數(shù)轉(zhuǎn)換為字符串,那么可以試想,如果每次取得回文數(shù)的最末尾數(shù)字,除了第一次,后面每次取都將前面的數(shù)乘以10,最后應(yīng)該得到最原始的x
((((個(gè)位)*10+十位)*10+百位)。。。。。)= x
class Solution {public boolean isPalindrome(int x
) {if(x
==0){return true;}if(x
<0 || x
%10==0){return false;}int temp
=x
;int y
=0;while(temp
!=0){y
=y
*10+temp
%10;temp
/=10;}return x
==y
;}
}
提交結(jié)果顯示,第二種方法比第一種運(yùn)行時(shí)間更短,效率更高。
總結(jié)
以上是生活随笔為你收集整理的力扣09-回文数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。