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.

 

直接的思路就是每次将最高位和最低位相比,直到只剩下0个或1个数字。

要求最高位就必须要知道基数(10的n次方),每次取了最高位和最低之后,基数是要除以100的,当基数小于1的时候就不需要比较了。

因为输入是int类型,求基数的时候要注意不要overflow。

如果要以x / m > 0 来求基数的话,那么注意m要用long long类型。 不过最好是用 x /m >=10 来判断。

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if (x < 0) return false;
 5         if (x < 10) return true;
 6         int m = 1; // long long m = 1
 7         while (x / m >= 10) { //x / m > 0
 8             m *= 10;
 9         }
10         //m /= 10;
11         int l, r;
12         while (m > 1) {
13             l = x / m;
14             x = x % m;
15             m /= 100;
16             r = x % 10;
17             x = x / 10;
18             if (l != r) return false;
19         }
20         
21         return true;
22     }
23 };

 

 

转载于:https://www.cnblogs.com/linyx/p/3702743.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值