首页 > 代码库 > Leetcode | Palindrome Number
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 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。