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: x = 121
Output: true
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.
Example 4:
Input: x = -101
Output: false
Constraints:
-2^31 <= x <= 2^31 - 1
这道题意思就是要我们实现一个函数,这个函数是判断输入的一个数字倒过来读还是不是原来的数字,如果是就返回true
,不是就返回false
。
第一步:将整型转为字符串型;
第二步:声明左指针i
和右指针j
,每次将左指针i
向右移动一位,右指针j
向左移动一次;
第三步:做判断,如果左右指针对应的字符相等,则继续推进,直到将字符串全部遍历完后返回true
,否则返回false
。
func isPalindrome(x int) bool {
xs := strconv.Itoa(x) // 整型转换为字符串
for i, j := 0, len(xs)-1; i < j; i, j = i+1, j-1 {
//i从左开始,j从右开始,i递增,j递减,逐个判断下标i和j对应的数字是否相等
if xs[i] != xs[j] {
return false
}
}
return true
}
执行结果:
leetcode-cn执行:
执行用时:28 ms, 在所有 Go 提交中击败了26.90%的用户
内存消耗:5.3 MB, 在所有 Go 提交中击败了19.58%的用户
leetcode执行:
Runtime: 28 ms, faster than 21.90% of Go online submissions for Palindrome Number.
Memory Usage: 5.6 MB, less than 14.02% of Go online submissions for Palindrome Number.