首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-9. Palindrome Number | 回文数

LeetCode-9. Palindrome Number | 回文数

作者头像
Zoctopus
发布2021-02-22 14:42:45
3320
发布2021-02-22 14:42:45
举报

题目

LeetCode LeetCode-cn

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.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-02-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
    • 解法一:双指针法
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档