您的位置:首页 > 编程语言 > PHP开发

LeetCode:Reverse Integer

2012-02-27 05:45 330 查看
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).

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

class Solution {
public:
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
double result = 0, multi = 1;
vector<int> digit;
int tmp = 0, flag = 0;
if(x > 0)
flag = 1;
else
{
flag = -1;
x = -1 * x;
}

while(x != 0)
{
tmp = x % 10;
x = x / 10;
digit.push_back(tmp);
}

while(digit.size() != 0)
{
result = result + digit.back() * multi;
multi = multi * 10;
digit.pop_back();
}

result = result * flag;

if(result > INT_MAX)
{
//cout<<"boom"<<endl;
return INT_MAX;
}
if(result < INT_MIN)
return INT_MIN;

return result;

}
};

int main()
{
Solution ss;
//cout<<INT_MAX;
cout<<"result: "<<ss.reverse(-1147483647)<<endl;
}


Round 2:

class Solution {
public:
int reverse(int x) {
long result = 0;
long multi = 1;
long temp = x;
temp = std::abs(temp);
while(temp > 9)
{
temp /= 10;
multi *= 10;
}
temp = x;
temp = std::abs(temp);
while(temp > 0)
{
result += (temp%10) * multi;
temp /= 10;
multi /= 10;
}
result = x > 0 ? result : 0-result;
if(result > INT_MAX || result < INT_MIN)
return 0;
else
return result;
}
};


Round 3:

class Solution {
public:
int reverse(int x) {
int result = 0;
while(x != 0)
{
if(x > 0 && (result > INT_MAX/10 || ((result == INT_MAX/10) && (x%10 > INT_MAX%10))))
{
return 0;
}
if(x < 0 && (result < INT_MIN/10 || ((result == INT_MIN/10) && (x%10 < INT_MIN%10))))
{
return 0;
}
int digit = x % 10;
x /= 10;
result = result*10 + digit;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息