---
# System prepended metadata

title: LeetCode 7. Reverse Integerr
tags: [Leetcode]

---

---
title: 'LeetCode 7. Reverse Integerr'
disqus: hackmd
---

# LeetCode 7. Reverse Integer



## Description

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

Input: x = 123
Output: 321

Input: x = -123
Output: -321

## Constraints

-2^31^ <= x <= 2^31^ - 1

## Answer

此題可藉由取餘數將每個數字都抓出，然後再檢查有無overflow，若有就return 0，若無就繼續做計算，直到x完全解析完成即可return ans。

```Cin=
int reverse(int x){
    int ans = 0, tmp = 0, flag = 0;
    if(x<0){flag = 1;}
    while(x){
        tmp = x%10;
        if(!flag && ans > (INT_MAX-tmp)/10){return 0;}
        if(flag && ans < (INT_MIN-tmp)/10){return 0;}
        ans = ans * 10 + tmp;
        x/=10;
    }
    return ans;
}
```



## Link
https://leetcode.com/problems/reverse-integer/
###### tags: `Leetcode` 
