[LeetCode] Palindrome Number


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.

 

每次,取出數的最高位和最低位比較,這里設置一個base為10^n,用來取出數的最高位,每次循環除以100,因為每次數會消去2位。

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (x < 0)
 7             return false;
 8         if (x == 0)
 9             return true;
10             
11         int base = 1;
12         while(x / base >= 10)
13             base *= 10;
14             
15         while(x)
16         {
17             int leftDigit = x / base;
18             int rightDigit = x % 10;
19             if (leftDigit != rightDigit)
20                 return false;
21             
22             x -= base * leftDigit;
23             base /= 100;
24             x /= 10;
25         }
26         
27         return true;
28     }
29 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM