[leetCode]Easy — Reverse Integer解題紀錄

Champion Hsieh
Firmware_Engineer
Published in
1 min readJun 20, 2021

Question:

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 [-2^31, 2^31 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

給一個 32bit的整數x,回傳x的顛倒數值,但如果x的值超過32bit整數的範圍,則回傳0。

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Solution:

#include <math.h>int reverse(int x){
int ans = 0;
if(x>=INT_MAX || x<=INT_MIN) return 0;

if(x>0){
while(x){
if (ans > INT_MAX/10) return 0;
ans = ans*10 + x % 10;
x /= 10;
}
return ans;
}else{
x = 0 - x;
while(x){
if (ans > INT_MAX/10) return 0;
ans = ans*10 + x % 10;
x /= 10;
}
ans = 0 - ans;
return ans;
}
}

--

--