LeetCode3:迴文數

題幹描述:

判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。

最初想法:


class Solution {
    public boolean isPalindrome(int x) {
        String a = Integer.toString(x);
        char b [] = a.toCharArray();
        while(b[0] != '-'){
            for (int i = 0; i <= b.length/2;i++ ){
            	if(b[i] == b[b.length - 1 - i]){
                	return true;
            	}else{
                	return false;
            		}
            	} 
        }              
        return false;
    }
}

然後提交報錯,發現循環結構有問題,更改後通過。

public boolean isPalindrome(int x) {
    String a = Integer.toString(x);
    char b [] = a.toCharArray();
    while(b[0] != '-'){
        for (int i = 0; i <= b.length/2; i++ ){
            if(b[i] == b[b.length - 1 - i]){
                continue;
            }
            return false;
        }
        return true;
    }
    return false;
}

數學解法:



class Solution {
    public boolean isPalindrome(int x) {
        int a = x;
        if(x < 0){
            return false;
        }
        if(x < 10){
            return true;
        }
        if(x % 10 == 0){
            return false;
        }
        int t = 0;
        while(x > 0){
            t = t * 10 + x % 10;
            x /= 10;
        }
        return t == a;
    }
}

藉助函數:


class Solution {
    public boolean isPalindrome(int x) {
        String reversedStr = (new StringBuilder(x + "")).reverse().toString();
        return (x  + "").equals(reversedStr);
    }
}

發佈了26 篇原創文章 · 獲贊 4 · 訪問量 4453
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章