leetcode算法题—golang—回文数(题9)

题目:回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true
示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

方法一:

func isPalindrome(x int) bool {
	if x<0 {
		return false
	}
	strn := strconv.FormatInt(int64(x),10)
	strnLen := len(strn)
	//找出中间数
	r1 := judgeIsPalindrome(strn,strnLen/2-1,strnLen/2+1)
	r2 := judgeIsPalindrome(strn,strnLen/2-2,strnLen/2+1)
	if r1 ||(r2&& strn[strnLen/2-1]==strn[strnLen/2]) {
		return true
	}
	return false
}

func judgeIsPalindrome(str string,start int,end int)bool{

	for start >=0 && end < len(str) &&str[start] == str[end]{
		start--
		end++
	}
	if start ==-1 && end == len(str){
		return true
	}
	return false
}

方法二:

func isPalindrome(x int)bool{

	if x <0{
		return false
	}
	res :=0
	n :=x
	for ;x!=0;x /=10{
		res =res*10 + x%10
	}
	return n==res
}

方法三(奇数->如果数字的长度是奇数位,去除位于中位置的数)

参考链接:https://leetcode-cn.com/problems/palindrome-number/solution/

func isPalindrome3(x int)bool{

	//排除小于0,和最后以为是0的情况
	if x <0 || (x%10==0 && x !=0){
		return false
	}

	temp :=0
	//这样能够做避免你转换后出现溢出的现象
	for x>temp{
		temp = temp*10+x%10
		x /=10
	}
	//如果是奇数的话,则temp/10,舍去最后一位,在做比较
	return x==temp || x==temp/10
}

推荐:方法三

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值