[LeetCode] Palindrome Number

要是面试遇到这道题,估计要挂了,想了很久才做出来。

因为不许使用多余的空间,所以一开始想的是两头缩小,比如12321->232->3,最后认为对称。结果遇到1021就失败了,02变成2,也认为两边对称。后来就想多了,觉得有什么特殊的算法,最后又回到这个想法,中间开始缩小。

虽然代码有点Ugly,很长,很容易出错,但值得欣慰的是完全按照要求来的,呵呵一下吧。

class Solution {
public:
    bool isPalindrome(int x) {
		if (x < 0) {
			return false;
		}

		if (x >= 1000000000) {
			if (x / 100000 % 10 == x % 100000 / 10000) {
				x = x % 10000 + x / 100000 * 10000;
				return isPalindrome(x);
			}
			else {
				return false;
			}
		}
		else if (x >= 100000000) {
			x = x % 10000 + x / 100000 * 10000;
			return isPalindrome(x);
		}
		else if (x >= 10000000) {
			if (x / 10000 % 10 == x % 10000 / 1000) {
				x = x % 1000 + x / 100000 * 1000;
				return isPalindrome(x);
			}
			else {
				return false;
			}
		}
		else if (x >= 1000000) {
			x = x % 1000 + x / 10000 * 1000;
			return isPalindrome(x);
		}
		else if (x >= 100000) {
			if (x / 1000 % 10 == x % 1000 / 100) {
				x = x % 100 + x / 10000 * 100;
				return isPalindrome(x);
			}
			else {
				return false;
			}
		}
		else if (x >= 10000) {
			x = x % 100 + x / 1000 * 100;
			return isPalindrome(x);
		}
		else if (x >= 1000) {
			if (x / 100 % 10 == x % 100 / 10) {
				x = x % 10 + x / 1000 * 10;
				return isPalindrome(x);
			}
			else {
				return false;
			}
		}
		else if (x >= 100) {
			x = x % 10 + x / 100 * 10;
			return isPalindrome(x);
		}
		else if (x >= 10) {
			if (x / 10 == x % 10) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return true;
		}
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值