您的位置:首页 > 其它

leetcode [007] : Reverse Integer

2015-09-15 11:56 453 查看
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.

Update (2014-11-10): Test cases had been added to test the overflow behavior.

思路:

按照题意,最主要是处理越界问题

1、分离出每一个数字的方法就是x % 10,可以把分离之后的数字加上'0',变为这个数字的字符

2、转换的过程中注意把开头的那些0全部去掉

3、字符串变为数字的方法就是从头到尾不断乘以10,在程序中可以直接使用atoi来代替

4、使用atoi之前务必使传入的字符串是合法的

5、合法性:

    A、如果为0x80000000,也就是INT_MIN,值等于-2147483648,转换之后等于-8463847412,不合法

    B、有没有可能转换完了之后刚好等于-2147483648(因为单单按照字符串判断,正数要比负数小一个1),逆推了一下,不可能

      所以,判断的标准为 : 字符串等长情况下,大于2147483647的字符串即是越界

6、最后还原正负号即可

源代码如下:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution {
public:

int reverse(int x) {
bool bNeg = false;
if (x == 0 || x == 0x80000000) return 0;
if (x < 0)
{
bNeg = true;
x = -x;
}

string strNums;
int iTemp;
while (x)
{
iTemp = x % 10;
x = x / 10;
if (iTemp == 0 && strNums.size() == 0) continue;
strNums += ('0' + iTemp);
}

//check if string is legal (large than MAX_INT or not)
const string strMax = "2147483647";
bool bLegal = false;
if (strNums.size() < strMax.size() || strNums <= strMax)
{
bLegal = true;
}

if (!bLegal) return 0;
iTemp = atoi(strNums.c_str());
if (bNeg) iTemp = -iTemp;
return iTemp;
}
};

int main()
{
Solution a;
int iNum = a.reverse(123450);
printf("%d\n", iNum);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: