0x00 问题描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
判断一个整数是否为palindrome (如果一个整数正序等于倒序则是palindrome)

Example:

Input: 121
Output: true

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

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.

0x01 问题分析

参考 Question 7. Reverse Integer [easy]
首先对整数进行倒序,如果倒序结果等于输入,则返回true
特别注意负数,负数的倒序和正序是不一样的,这里符号也进行了倒序。

0x02 Go代码

const int32_Max = 2147483647
const int32_Min = -2147483648
func isPalindrome(x int) bool {
    if x < 0 {return false}
    temp_x := x
    return_value := 0
    for {
        _mod := x%10
        x /= 10
        if return_value > int32_Max/10 || (return_value == int32_Max/10 && _mod > 7) {return false}
        if return_value < int32_Min/10 || (return_value == int32_Min/10 && _mod < -8) {return false}
        //判断上一个操作以及接下来的补位是否会导致溢出
        return_value = return_value*10 + _mod
        if x == 0 {break}
    }
    return return_value == temp_x
    
}

标签: Golang, LeetCode

添加新评论