LeetCode9 Palindrome Number
题意:
Determine whether an integer is a palindrome. Do this without extra space. (Easy)
分析:
自己考虑的方法是利用Reverse Integer,然后查看rev与x是否相等,注意负数和0的判断(这里WA了一次)
代码1:
1 class Solution { 2 private: 3 int reverse(int x) { 4 long long result = 0; 5 while (x != 0) { 6 int temp = x % 10; 7 x /= 10; 8 result = result * 10 + temp; 9 if (result > 0x7FFFFFFF || result < -0x7FFFFFFF) { 10 return 0; 11 } 12 } 13 return result; 14 } 15 public: 16 bool isPalindrome(int x) { 17 if (x < 0) { 18 return false; 19 } 20 int rex = reverse(x); 21 if (rex == 0 && x != 0) { //溢出(不是因为等于0而得到rex = 0) 22 return false; 23 } 24 if (rex == x) { 25 return true; 26 } 27 return false; 28 } 29 };
查看讨论区,有只比较一半的解法,循环中的思路和reverse integer类似,更为简洁,实现如下;
代码2:
1 class Solution { 2 public: 3 bool isPalindrome(int x) { 4 if (x < 0 || (x % 10 == 0 && x != 0) ) { 5 return false; 6 } 7 int sum = 0; 8 while (x > sum) { 9 int temp = x % 10; 10 sum = sum * 10 + temp; 11 x /= 10; 12 } 13 if (x == sum || x == sum / 10) { 14 return true; 15 } 16 return false; 17 } 18 };