标签:string iso sed ref plain its relative integer top
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution { public : bool isPalindrome( int x) { if (x < 0) return false ; long num = x,result = 0; while (num){ result = result * 10 + num %10; num/=10; } if ( result == x) return true ; else return false ; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution { public : bool isPalindrome( int x) { if (x<0) return false ; if (x<10) return true ; if (x%10==0) return false ; //actual logic int v=x%10; x=x/10; while (x-v>0) //x is getting smaller every step, { v=v*10+x%10; x/=10; } if (v>x){v/=10;} return v==x? true : false ; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Solution { public : bool isPalindrome( int x) { if (x < 0) return false ; int d = 1; // divisor while (x / d >= 10) d *= 10; // 计算出是多少位数 while (x > 0) { int q = x / d; // quotient int r = x % 10; // remainder if (q != r) return false ; x = x % d / 10; d /= 100; } return true ; } }; |
标签:string iso sed ref plain its relative integer top
原文地址:http://www.cnblogs.com/zhxshseu/p/27ea3ddf3ceda4bbd5c090b514b28c13.html