标签:style blog class code java ext javascript color int string http
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 };
Leetcode | Palindrome Number,布布扣,bubuko.com
标签:style blog class code java ext javascript color int string http
原文地址:http://www.cnblogs.com/linyx/p/3702743.html