Daily bit(e) of C++ | Reverse an integer
Daily bit(e) of C++ #275, Common interview problem: Reverse an integer.
Today, we will look at a common C++ interview problem: Reverse an integer.
Given a 64-bit integer, reverse its (decimal) digits. If the reversed number cannot be represented, throw std::domain_error.
For example, for the input -123456789, the result should be -987654321; for the input 100, the result should be 1 (i.e. 001, ignoring leading zeroes).
Before you continue reading the solution, I encourage you to try to solve it yourself. Here is a Compiler Explorer link with a couple of test cases: https://compiler-explorer.com/z/a7GbcG3vb.
Solution
The basic approach of reversing the digits is straightforward: repeatedly dividing the source number by ten, multiplying the result by ten and adding the modulo.
However, we need to be careful about the potential over or under-flow. This can happen as part of the multiplication or when adding the modulo.