1. 程式人生 > >LeetCode(9)判斷迴文數

LeetCode(9)判斷迴文數

問題:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.Coud you solve it without converting the integer to a string?

在真實面試中也是遇到過的問題。

採用java解決

class Solution {
    /**
     * 思路
     * 1,建立一個list集合,遍歷原數的每一位,推入集合
     * 2,遍歷集合,判斷每一位與最後一位回退的數是否相等,不等直接返回false
     * 3,最後直接返回true
     */
    //建立存放每一位的集合
    private List list = new ArrayList();
    //建立推入集合每位數的方法
    public void pushInt(int x){
        if(x < 10){
            this.list.add(x);
        }else{
            while(x != 0){
                this.list.add(x % 10);
                x /= 10;
            }
        }
    }
    //建立遍歷集合,判斷是否為迴文數的方法
    public boolean isListPalindrome(int x){
        int size = this.list.size();
        int mid = size/2;
        boolean flag = true;
        for(int i = 0; i <= mid; i++){
            if(this.list.get(i) != this.list.get(size-1-i)){
                flag = false;
                return flag;
            }
        }
        return flag;
    }
    public boolean isPalindrome(int x) {
        if(x < 0){
            return false;
        }else if(x < 10){
            return true;
        }else{
            this.pushInt(x);
            return this.isListPalindrome(x);
        }
    }
}