[leetcode] 9. Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

判断一个数字是不是回文数。负数肯定不是。10以内的正数和0都是。大于等于10的就要分别判断了。这道题最容易想到的就是把数字转化为一个字符串,这样再对字符串求是否回文就可以了。但是题目要求不能有额外使用空间(感觉这里说的不太严谨,另外定义几个辅助数字不算额外空间么?)。再一个思路就是“Reverse Integer”,可惜出题的人已经把这条路堵死了,因为可能出现溢出。

所以最终的思路就是不断分解出整数的最高位和最低位,看是否相等,如果不相等就返回false,相等的话就继续,然后处理整数使其去掉最高位和最低位,最后知道其为0为止,返回true。

java代码

public class Solution {
    public boolean isPalindrome(int x) {
        if (x<0){
            return false;
        }else if(x<10){
            return true;
        }else{
            int tmp=x;
            int base = 1;
            int left=0,right=0;
            while(tmp/10>0){
                base*=10;
                tmp/=10;
            }
            tmp=x;
            while(tmp>0){
                left=tmp/base;
                right=tmp%10;
                if(left!=right){
                    return false;
                }
                
                tmp-=left*base;
                tmp/=10;
                base/=100;//去掉了最高位,还去掉了最低位,所以这里是100而不是10
            }
        }
        return true;
    }
}


go代码

func isPalindrome(x int) bool {
    if x < 0 {
		return false
	}
	var tmp int = x
	var base int = 1
	for {
		if tmp/10 > 0 {
			base *= 10
			tmp /= 10
		} else {
			break
		}
	}
	tmp = x
	var left, right int
	for {
		if tmp == 0 {
			break
		}
		left = tmp / base
		right = tmp % 10
		if left != right {
			return false
		} else {
			tmp -= left * base
			tmp /=10
			base /= 100
		}
	}
	return true
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值