Leetcode-Palindrome Number

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

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.


题目给出一个数字,判断该数字是否是回文结构,即该数字从左往右看,或,从右往左看,是一样的。按照题目要求,不处理负数。虽然题目写着不能使用额外空间,但确实可以创建一个变量。原题评论里也有人在问“the restriction of using extra space”究竟算是啥意思,不是很懂,反正先做下去再说。

方法比较简单,直接提取数字的末位,构造新的数字,再比较是否相等。若新数字等于原数字,则原数字是回文。要注意,每次都要去掉原数字的末位,以便取得“新的”末位。

class Solution_1 {
public:
    bool isPalindrome(int x) {
        if(x < 0 || (x%10 == 0 && x != 0)) {
        	return false;
        }
		int t = 0;
		int k = x;
		while(k > 0) {
		t = t*10 + k%10;
		k = k/10;
		}
		return x==t || x == t/10;
    }
};

另一个更加直观的方法是,每次提取数字的首位和末位,判断是否相等。

class Solution_2{
public:
    bool isPalindrome(int x) {
        if(x < 0 || (x%10 == 0 && x != 0)) {
        	return false;
        }
        int t = 1;
        while(t <= x) {
        	t = t*10;
        }
        t = t/10;
        while(x > 0) {
        	if(x%10 != x/t) {
        		return false;
        	}
        	x = x%t;//去掉第一位 
        	x = x/10;//去掉最后一位 
        	t = t/10;
        }
        return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值