Fork me on GitHub
打赏

LeetCode-9. Palindrome Number | 回文数

题目

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.

参考资料

posted @   Zoctopus_Zhang  阅读(63)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
// function btn_donateClick() { var DivPopup = document.getElementById('Div_popup'); var DivMasklayer = document.getElementById('div_masklayer'); DivMasklayer.style.display = 'block'; DivPopup.style.display = 'block'; var h = Div_popup.clientHeight; with (Div_popup.style) { marginTop = -h / 2 + 'px'; } } function MasklayerClick() { var masklayer = document.getElementById('div_masklayer'); var divImg = document.getElementById("Div_popup"); masklayer.style.display = "none"; divImg.style.display = "none"; } setTimeout( function () { document.getElementById('div_masklayer').onclick = MasklayerClick; document.getElementById('btn_donate').onclick = btn_donateClick; var a_gzw = document.getElementById("guanzhuwo"); a_gzw.href = "javascript:void(0);"; $("#guanzhuwo").attr("onclick","follow('33513f9f-ba13-e011-ac81-842b2b196315');"); }, 900);
点击右上角即可分享
微信分享提示