题目:回文数
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 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
}
推荐:方法三