想开始尝试刷一下leetcode,挑了一题最简单的开始,也算是给自己的刷题之路一个开门红吧。
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
int reverse(int x)
{
}
我们在函数里面是无法判断x是否溢出的,这件事情应该是在用户输入的时候考虑的,而且还不能是cin>>x;
#include<iostream>
using namespace std;
class Solution {
public:
int reverse(int x) {
bool isMinus = false;
int tempX = x;
if(x<0)
{
tempX = -tempX;
isMinus = true;
}
int result = 0;
while(tempX!=0)
{
result = result*10 + tempX%10;
tempX = tempX/10;
}
if(isMinus)
result = -result;
return result;
}
};
int main()
{
Solution solution;
cout<< solution.reverse(123)<<endl;
cout<< solution.reverse(-123)<<endl;
cout<< solution.reverse(12300)<<endl;
cout<< solution.reverse(-12300)<<endl;
cout<< solution.reverse(0)<<endl;
return 0;
}