Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Reverse Integer - Solution/C++

7. Reverse Integer

Question:

Given a 32-bit signed integer, reverse digits of an integer.

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Example:

Input: x = 123
Output: 321

Input: x = -123
Output: -321

Input: x = 120
Output: 21

Input: x = 0
Output: 0

Constraints:
  • -2^31 <= x <= 2^31 -1
  • Source code

    Version 1

    Idea:
    At the begining, I need to get units digit, so the modulus operator % can compute the remainder. Then, the remainder should be added to answer(return value) after answer times ten for each loop. x = x / 10 means removing units digit for getting hundreds digit. Don't forget the constraints, use values of INT_MIN and INT_MAX to implement it.
    P.S. return (conditional)?true:false

    Time complexity: O(floor(log(10)(x)) + 1)
    Space complexity: O(1)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Solution {
    public:
    int reverse(int x) {
    long ans = 0;
    while(x != 0){
    ans = ans * 10 + x % 10;
    x = x / 10;
    }
    return (ans>INT_MIN && ans<INT_MAX)?ans:0;
    }
    };