
前言
给定一个整数 x,如果 x 是回文整数,则返回 true。
当一个整数向后读与向前读相同时,它就是回文。例如,121 是回文,而 123 不是。
示例 1
输入: x = 121
输出: 真
示例 2
输入: x = -121
输出: 假
说明: 从左到右依次为 -121。 从右到左,它变成 121-。 因此它不是回文。
示例 3
输入:x = 10
输出: 假
说明: 从右到左读取 01。 因此它不是回文。
示例 4
输入:x = -101
输出: 假
约束条件:
**跟进:**你能在不将整数转换为字符串的情况下解决它吗?
class PalindromeNumber {
func isPalindrome(x: Int) -> Bool {
guard x >= 0 else {
return false
}
var x = x
var div = 1
while (x / div >= 10) {
div = div * 10
}
while (x > 0) {
var left = x / div
var right = x % 10
if (left != right) {
return false
}
x = (x % div) / 10
div = div / 100
}
return true
}
}
该算法题解的仓库:LeetCode-Swift[2]
点击前往 LeetCode[3] 练习
[1]
@故胤道长: https://m.weibo.cn/u/1827884772
[2]
LeetCode-Swift: https://github.com/soapyigu/LeetCode-Swift
[3]
LeetCode: https://leetcode.com/problems/palindrome-number/