标签:
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:reverse integer
1 class Solution { 2 public: 3 bool isPalindrome(int x) { //Runtime:80ms 4 if(x<0)return false; 5 if(x==reverse(x)){ 6 return true; 7 }else{ 8 return false; 9 } 10 } 11 int reverse(int x) 12 { 13 long long result=0; 14 15 while(x!=0){ 16 result=result*10+x%10; 17 x/=10; 18 } 19 20 if(result>INT_MAX)return 0; 21 22 return result; 23 } 24 };
Solution 2 :int 转化为string
1 #include<string> 2 #include<sstream> 3 using namespace std; 4 5 bool isPalindrome(int x) { //Runtime:108ms 6 stringstream ss; 7 ss<<x; 8 string str=ss.str(); 9 for(int i=0,j=str.size()-1;i<j;i++,j--){ 10 if(str[i]!=str[j])return false; 11 } 12 return true; 13 }
【LeetCode】9 - Palindrome Number
标签:
原文地址:http://www.cnblogs.com/irun/p/4681436.html