Given a 32-bit signed integer, reverse digits of an integer.
Naive solution with C++ is using
mod operator to get the right-most bit of number, accumulate to a result.
Note 1: If input is 0, return 0 as result directly.
Note 2: Remember to test valid integer range in the loop, using
long long for simple logic.
If we don’t use
long long type, it will be more complicated to number range validation.
Approach with string
If you don’t want the numeric operations, another approach is convert the integer into string. In this way we don’t need to care the number range issue, but need to take care the negative corner cases.
Preparing for an interview? Check out this!
Join my Email List for more insights, It's Free!😋