Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321 Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
思路: 注意符号,溢出。
class Solution { public: int reverse(int x) { int tag = 1; if(x < 0){ tag = -1; x *= -1; } int k = 0, y = 0; while(x > 0){ y = y * 10 + (x % 10); x /= 10; } if(y < 0) printf("Overflow!\n"); return (y * tag); } };
Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
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.
思路: 注意负数和溢出情况都是 false. 其余情况,就是反转再判断,参考上题.
class Solution { public: bool isPalindrome(int x) { if(x < 0) return false; int v = x, y = 0; while(v > 0){ y = y * 10 + (v % 10); v /= 10; } if(y == x) return true; return false; // 注意:溢出时,也肯定是 false! } };