1. 程式人生 > >Palindrome Number之Java實現

Palindrome Number之Java實現

nat nbsp get example ole 取余 等於 public xpl

一、題目

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:Coud you solve it without converting the integer to a string?

二、解題思路

1、此題為判斷一個數值是否是回文數,即將數值反轉後是否等於原數值,如是,則為回文數;
2、先判斷數值x是否小於0,如小於0則返回false;
3、再判斷x是否等於0,如是,則返回true;
4、如上面兩種情況都不符合,則將數值x循環取余取出每一位上的數存入集合中;

5、循環將集合中的數取出,求得反轉後的數值;
6、與數值x比較是否相等,如是,則返回true,否則返回false。

三、代碼實現

public boolean isPalindrome(int x) {
    if (x < 0) {
        return false;
    } else if (x == 0) {
        return true;
    } else {
        int temp = x;
        int result = 0;
        List<Integer> list = new ArrayList<Integer>();

        while (temp != 0) {
            list.add(temp % 10);
            temp = temp / 10;
        }

        for (int i = 0; i < list.size(); i++) {
            result = result + list.get(i) * (int)Math.pow(10, list.size() - 1 - i);
        }

        if (result == x) {
            return true;
        } else {
            return false;
        }
    }
}

Palindrome Number之Java實現