问题描述:
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?
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.
https://leetcode.com/problems/reverse-integer/description/
思路分析:将一个int值的低位与高位互换,并保持原来的符号不变。要注意的是int的范围为-2147483648~2147483647,所以有些int值反转之后会出现overflow,此时应当作出相应的异常处理。基本思路就是使用模除10来不断找到最小位,然后加不断加起来。为防止溢出,是存放在一个long变量中的,进行判断之后再返回。
代码:
class Solution {
public:
int reverse(int x) {
long n = 0;
while(x!=0){
n = x%10+10*n;
x = x/10;
}
if (n>INT_MAX||n<INT_MIN){
return 0;
}
return n;
}
};
时间复杂度:O(logn)
反思:很简单的一道题目,但是一开始思考的时候就跑偏了,想用字符串来处理,造成了很多麻烦,但是也学习了很多东西。stringstream来处理string的强制转化;char array[]数组存储string数据;string的.length()和.c_str()方法;atoi(),atol()的字符串转数字的强制转换;如何设计自己函数。但是大方向的错误带来的是整体的复杂化,以后的头脑要清醒。
class Solution {
public:
int reverse(int x) {
int sign=1;
int a=x,l=0;
long result=0;
stringstream ss;
string str;
if (x<0)
{
sign=-1;
a=x*(-1);
}
ss<<a;
ss>>str;
l=str.length();
char s[l];
for (int i = 0; i < l; ++i)
{
s[i] = str[i];
}
rev(s,l);
str=s;
result=atol(str.c_str());
result=result*sign;
if (result>INT_MAX||result<INT_MIN){
return 0;
}
return result;
}
void rev(char *s, int n){
for (int i=0,j=n-1;i<j;i++,j--)
{
char c =s[i];
s[i]=s[j];
s[j]=c;
}
}
};