Home Reverse Integer
Post
Cancel

LeetCode #7: Reverse Integer (C/C++).

medium

source: https://leetcode.com/problems/reverse-integer/
C/C++ Solution to LeetCode problem 7. Reverse Integer.

Problem


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).

Examples


Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Constraints


  • -231 <= x <= 231 - 1

Solution


  • We initialize a new number (our result) to 0.
  • We just divide by 10 the number ang get the module.
  • We multiply by 10 our result and then we add the module of the previous step.
  • We continue until we can not get more modules.
  • For each step, we calculate if the result will be outside the range once multiplied by 10, if so, we return 0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
  int reverse(int x) {
    int tmp = x;
    int result = 0;
    int d;

    while (tmp != 0) {
      d = tmp % 10;
      if ((INT_MAX/10) - abs(result) < 0)
        return 0;

      result = (result * 10) + d;
      tmp /= 10;
    }

    return result; 
  }
};
This post is licensed under CC BY 4.0 by the author.

Zigzag Conversion

String to Integer (atoi)