来源:Leetcode
原帖:http://oj.leetcode.com/problems/reverse-integer/
题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this? 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).
Solution: Use % and / iteratively.
例-8%3=-2; -8%-3=-2; 8%-3=2
负数求余主要看的是被除数,与除数无关。
如果被除数是负数那么其结果一定为负。如果被除数和除数都为负则结果还是为负。
如果被除数为正,除数为负,结果为正。
代码:
1] 考虑INT_MAX
2] 考虑long long
原帖:http://oj.leetcode.com/problems/reverse-integer/
题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this? 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).
Solution: Use % and / iteratively.
例-8%3=-2; -8%-3=-2; 8%-3=2
负数求余主要看的是被除数,与除数无关。
如果被除数是负数那么其结果一定为负。如果被除数和除数都为负则结果还是为负。
如果被除数为正,除数为负,结果为正。
代码:
1] 考虑INT_MAX
class Solution {
public:
int reverse(int x) {
if (x == 0) return 0;
if (x > 0) return -reverse(-x);
int res = 0;
while (x) {
if (res < INT_MIN / 10 || res == INT_MIN / 10 && x % 10 < INT_MIN % 10) {
//throw invalid_argument("reverse integer overflows");
return 0;
}
res = res * 10 + (x % 10);
x /= 10;
}
return res;
}
};
2] 考虑long long
class Solution {
public:
int reverse(int x) {
long long res = 0; // long long
while (x) {
res = res * 10 + x % 10;
x /= 10;
}
assert( res >= INT_MIN && res <= INT_MAX); // overflow and assert usage.
return res;
}
};
No comments:
Post a Comment