LeetCode Algorithm #7 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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
解题
解题的过程是多种多样的,但是不外乎分为两个过程,一个是将输入翻转存在long long
类型中,一个是根据这个long long
数值判断是否溢出。
输入翻转
循环取余
循环取余即将输入的数字每次余10取出个位数,将这个个位数追加到翻转后数字的末尾,再将输入数字除10,直到输入数字变为0。
最朴素的方法就是使用基本运算符
long long y = 0;
while(x != 0) {
y = 10*y + x%10;
x /= 10;
}
另一种是使用<cstdlib>
中的div_t div(int numer, int denom)
函数,可以在返回的div_t
变量中取到商和余数。
long long revn = 0;
div_t r;
while(x != 0) {
r = div(x, 10);
revn = revn*10 + r.rem;
x = r.quot;
}
字符串反取
这种方法主要利用的是字符串,将输入转换为字符串,再从最后一位开始取将其转换为数字。不过要多加一个正负的判断。
bool negative = false;
if(x < 0) {
negative = true;
x = -x;
}
char buf[16];
sprintf(buf, "%d", x);
int length = strlen(buf);
long long result = 0;
for(int i = length-1; i >= 0; --i)
result = result*10 + (buf[i]-'0');
溢出判断
一种是使用强制转换为int
再转回long long
,与原来的值做比较是否有变化。
if((long long)((int)result) != result)
return 0;
另一种是直接和INT_MAX
比较,看是否超出了int
类型的上界。
if(abs(revn) > INT_MAX) {
revn = 0;
}
运行时间
结果是使用强制转换要比取绝对值判断大小要快得多,而翻转这一块则相差得不多。不过个人水平有限,这些方法在所有submissions中都不算快。并且相同的代码运行结果也不尽相同。
贴一个我的submissions中最快的12ms的代码
class Solution {
public:
int reverse(int x) {
bool negative = false;
if(x < 0) {
negative = true;
x = -x;
}
char buf[16];
sprintf(buf, "%d", x);
int length = strlen(buf);
long long result = 0;
for(int i = length-1; i >= 0; --i)
result = result*10 + (buf[i]-'0');
if((long long)((int)result) != result)
return 0;
return negative ? -(int)result : (int)result;
}
};