Palindrome Number ---- LeetCode 009
Posted 徐岩
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Palindrome Number ---- LeetCode 009相关的知识,希望对你有一定的参考价值。
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.
Solution 1: (with extra space)
1 class Solution 2 { 3 public: 4 bool isPalindrome(int x) 5 { 6 if(x == 0) return true; 7 if(x < 0) return false; 8 9 vector<int> v; 10 bool flag = true; 11 12 // 若x = 13314, 则v为4 1 3 3 1 13 while(x != 0) 14 { 15 v.push_back(x % 10); 16 x = x / 10; 17 } 18 19 auto left = v.begin(), right = prev(v.end()); 20 for(; left < right; ++left, --right) // 注意: left < right 21 { 22 if(*left != *right) 23 { 24 flag = false; 25 break; 26 } 27 } 28 return flag; 29 } 30 };
Solution 2:
class Solution { public: bool isPalindrome(int x) { if(x < 0) return false; else if(x == 0) return true; bool flag = true; int temp = x, y = 0; while(x != 0) { y = y * 10 + x % 10; x = x / 10; } if(y != temp) flag = false; return flag; } };
以上是关于Palindrome Number ---- LeetCode 009的主要内容,如果未能解决你的问题,请参考以下文章