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?

題目:

  判斷整數是否為回文,整數與回讀相同就是回文。

後續:

  試著不將整數轉成字串。

解答:

//把整數做反轉,再比對兩個數字是否一樣,即可驗證是否回文

public class PalindromeNumber9 {
    public static void main(String[] args) {
        System.out.print(isPalindrome(121));
    }
    public static boolean isPalindrome(int x) {
        if (x < 0 || (x > 0 && x % 10 == 0)) {
            return false;
        }
        int rev = 0;
        int num = x;
        while (num != 0) {
            rev = rev * 10 + num % 10;
            num = num / 10;
        }
        return rev == x;
    }
}

 

 

文章標籤
全站熱搜
創作者介紹
創作者 金城式 的頭像
金城式

金城式的程式筆記

金城式 發表在 痞客邦 留言(0) 人氣(6)