- 类静态变量需要在外部定义,且定义时不带static关键字;
- 对于数字常量默认为整型,如果表示范围大于整数的表示范围,会有编译告警,需要在后面加上U,例如,2147483648U,如果是long,需要加上UL,long long,则用LLU;
- 时间时间时间
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
class Solution {
public:
const static unsigned int max_int;
int reverse(int x)
{
int sign = (x >= 0) ? 1 : -1;
unsigned int abs_x = (x > 0) ? x : -x;
vector<unsigned int> v;
unsigned int mod = abs_x % 10, left = abs_x / 10;
v.push_back(mod);
for (; 0 != left;)
{
mod = left % 10, left = left / 10;
v.push_back(mod);
}
if (v.size() == 10 && v[0] > 2) // exception
{
return 0;
}
else // normal process
{
unsigned int result = 0, idx = 0;
for (vector<unsigned int>::iterator it = v.begin(); it != v.end(); ++it, ++idx)
{
result += (*it) * myPow(10, v.size() - idx - 1);
}
if ((result > Solution::max_int) || (result == Solution::max_int && sign > 0)) // exception
{
return 0;
}
else // normal process
{
return (int)result * sign;
}
}
}
int myPow(int x, int y)
{
int ret = 1;
for ( ;y != 0; y--)
{
ret *= x;
}
return ret;
}
};
const unsigned int Solution::max_int = 2147483648U;
int main()
{
Solution sol;
// example
int result = sol.reverse(123);
cout << result << endl;
result = sol.reverse(-123);
cout << result << endl;
result = sol.reverse(120);
cout << result << endl;
// exception
result = sol.reverse(0);
cout << result << endl;
result = sol.reverse(-1 * sol.myPow(2, 31));
cout << result << endl;
result = sol.reverse(-1 * sol.myPow(2, 31));
cout << result << endl;
return 0;
}