無聊多寫一題
我居然沒寫過這個ㄟ==
而且我居然一次過
老天保佑
7. Reverse Integer
Given a signed 32-bit integer x, return x with its digits reversed. If
reversing x causes the value to go outside the signed 32-bit integer range
[-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or
unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
就把負的跟奇怪的都特殊處理
int reverse(int x) {
int num_digits = 0;
// deal with negative
bool isneg = false;
if(x<0) {
if(x == INT_MIN) {
return 0;
}
isneg = true;
x = -x;
}
// calculate number of digits
int tmp = x;
while(tmp) {
num_digits += 1;
tmp = tmp/10;
}
// solve
int ans = 0;
bool check_overflow = (num_digits==10);
vector<int> digit_max = {7, 4, 6, 3, 8, 4, 7, 4, 1, 2};
for(int i=num_digits-1; i>=0; i