🔥

# 「Dart」Leetcodeの第9問「Palindrome Number」

2022/11/06に公開約3,200字

# 日本語版

## 問題

### 例1

``````入力: x = 121

``````

### 例2

``````入力: x = -121

``````

### 例3

``````入力: x = 10

``````

## 解決

もし数字が負であったり、最後の桁が「0」であれば、その数字は回文数でないことがわかります。

``````      if(x < 0 || (x != 0 && x % 10 == 0)){ if(x < 0 || (x != 0 && x % 10 == 0))
return false;
}
``````

もちろん、`0`は回文数です！

では、の数を格納する変数を作ってみましょう。

``````var reversedNumber = 0;
``````

ループが終了すると、reversedNumberが得られる。

``````    while(x > reversedNumber){
reversedNumber = reversedNumber * 10 + x % 10;
x = (x/10).floor();
}
``````

`reversedNumber``x` ( 初期値 ) と等しい場合、true を返す。等しくない場合は、false を返す。

``````return (x == reversedNumber || x == (reversedNumber/10).floor())? true: false;
``````

というわけで、コードは以下のようになるはずです。

``````class Solution {
bool isPalindrome(int x) {
if(x < 0 || (x != 0 && x % 10 == 0)){
return false;
}
var reversedNumber = 0;
while(x > reversedNumber){
reversedNumber = reversedNumber * 10 + x % 10;
x = (x/10).floor();
}
return (x == reversedNumber || x == (reversedNumber/10).floor())? true: false;
}
}
``````

# English ver.

## Problem

Given an integer `x`, return `true` if `x` is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

For example, `121` is a palindrome while `123` is not.

### Example 1

``````Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
``````

### Example 2

``````Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
``````

## Solution

So if the number is negative or if the last digit is `0`, then we know that the number is not a palindrome.

``````      if(x < 0 || (x != 0 && x % 10 == 0)){
return false;
}
``````

Of course, `0` is a palindrome!

Then let's create a variable that will store reversed numbers.

``````var reversedNumber = 0;
``````

Now, multiply the reversed variable with `10` and add the last digit of the number to it. Then, remove the last digit of `x`.

When the loop ends, we will have our `reversed number`.

``````    while(x > reversedNumber){
reversedNumber = reversedNumber * 10 + x % 10;
x = (x/10).floor();
}
``````

If the reversed number is equal to `x` ( initial number ), return true. If not, false.

``````return (x == reversedNumber || x == (reversedNumber/10).floor())? true: false;
``````

So, our code should look like this:

``````class Solution {
bool isPalindrome(int x) {
if(x < 0 || (x != 0 && x % 10 == 0)){
return false;
}
var reversedNumber = 0;
while(x > reversedNumber){
reversedNumber = reversedNumber * 10 + x % 10;
x = (x/10).floor();
}
return (x == reversedNumber || x == (reversedNumber/10).floor())? true: false;
}
}
``````

ログインするとコメントできます