题目描述
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 palindrome while 123 is not.
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.
Follow up:
Coud you solve it without converting the integer to a string?
解题思路一
转字符串数组法: 将数字变为字符串数组这道题, 进行前后判断
时间复杂度: O(n)
示例代码一
func isPalindrome(_ x: Int) -> Bool {
let strArray = Array.init("\(x)")
for index in 0..<strArray.count/2 {
if strArray[index] != strArray[strArray.count - index - 1] {
return false
}
}
return true
}
解题思路二
求回文数字法: 求出x 的倒序数字, 看与x是否相等
时间复杂度: O(n)
示例代码二
func isPalindrome(_ x: Int) -> Bool {
if x < 0 {
return false
}
var temp = x
var resultInt = 0
while temp > 0 {
resultInt = resultInt * 10 + temp % 10
temp = temp / 10
}
return resultInt == x
}