LeetCode:Palindrome Number
Posted 翎飞蝶舞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Palindrome Number相关的知识,希望对你有一定的参考价值。
9. Palindrome Number
Total Accepted: 111012 Total Submissions: 357341 Difficulty: Easy
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.
求出整数长度,将整数的后一半翻转,再跟前一半比较,这样肯定比原整数的值小,不可能发生溢出。注意,当整数位数为奇数时中间位的处理,我的方法中将该位删除了。
class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; int len = IntLen(x); int tmp = 0; for (int i = 0; i < len / 2; i++) { tmp = tmp * 10 + x % 10; x = x / 10; } if (len % 2 == 1) //若整数为奇数位,将中间一位删除 x = x / 10; if (tmp == x) return true; else return false; } int IntLen(int x) { int i = 0; while (x) { i++; x = x / 10; } return i; } };
以上是关于LeetCode:Palindrome Number的主要内容,如果未能解决你的问题,请参考以下文章