LeetCode #9. Palindrome Number プログラミング練習

問題:

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.

難易度: easy
入力: Int
目的: 入力された数字が回文かどうか判断せよ
出力: boolean
注意: 特になし

回文系の問題です。
前にString型の回文を判断をする問題があったと思いますが、整数の場合、Stringの様にCharacter[]に変換できないので、
まずは数字の長さを図る必要があります。
それ以外は特に注意することもなく初心者向けの簡単な問題です。

注意すべき事: 

  • マイナスの数字が入力された場合、回文にならないのでそのままfalseを返します。


以下回答です。

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0){
            return false;
        }
        int l = 0;
        int f = 0;
        int temp = x;
        int len = 1;
        while (temp >= 10){
            temp /= 10;
            len *= 10;
        }
        while (x > 0){
            f = x / len;
            l = x % 10;
            if(f != l){
                return false;
            }
            x = x % len / 10;
            len = len / 100;
        }
        return true;
    }
}

まず入力がマイナスでないか判断。
マイナスの場合”-”記号の為、回文にはならないのでFalse
入力された文字の最大位数を確認するためまずwhileでlenを回します。
例えば入力が121の場合、lenは100になります。
f = x/len = 1 (百の位)
l = x%10 = 1 (1の位)
f != l の場合false
次の循環に入る前、xへの処理が必要ですが、
私は確認済みの最小の位と最大の位の数字を取り除きました。
まずはx = x%len で最大の位を除き、x = x/10で最小の位を除きました。
二桁減ったのでlenはlen/100。
それを繰り返すだけで回文かどうか判断ができます。

今日は以上。
ではでは