Difficulty:

simple

Description:

Checks whether an integer is a palindrome. Palindromes are integers that read in positive (left to right) and backward (right to left) order.

The sample

1: Input: 121 Output:true
Copy the code
2: Input: -121 Output:falseInterpretation: Read from left to right as -121. Read from right to left, 121-. So it's not a palindrome number.Copy the code
3: Input: 10 Output:falseInterpretation: Read from right to left as 01. So it's not a palindrome number.Copy the code

Source: LeetCode link: leetcode-cn.com/problems/pa… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.


Language:

swift

Resolution:

Palindromes again, palindromes are the same backwards and forwards. Negative numbers are obviously not negative numbers, so let’s pass them out. And then to determine the positive number, one of the things I did here is I constructed two numbers and compared the left and right parts of the palindrome to see if they were equal. Left is the left half of the number and right is the reverse order of the right part of the number. This is a simple one, the remainder of 10 and so on. It is also important to note whether the length of the original number is odd or even.

The code is as follows:

class Solution {
    func isPalindrome(_ x: Int) -> Bool {
        if x < 0 {
            return false
        }
        var left = x, right = 0, index = 0
        let numberLength = String(x).count
        while index < numberLength / 2 {
            let end = left % 10
            right = right * 10 + end
            left /= 10
            index += 1
        }
        ifnumberLength % 2 ! = 0 { left /= 10 }if left == right {
            return true
        } else {
            return false}}}Copy the code

conclusion

Nothing to sum up.