Reverse Integer InterviewBit Solution

Problem: Reverse integer


Problem Description:

Reverse digits of an integer.


Example1:

x = 123,
return 321

Example2:

x = -123,
return -321

Return 0 if the result overflows and does not fit in a 32 bit signed integer



Approach


The approach is to extract the last digit of the number and push it to another number at the unit place.

For example, N = 123
Take R = 0    // To store reverse number.

Iteration 1: 
    Last_Digit = N % 10 = 3
    N = N / 10 = 12
    R = (R * 10) + Last_Digit = 0 + 3 = 3
    
Iteration 2:
    Last_Digit = N % 10 = 2
    N = N / 10 = 1
    R = (R * 10) + Last_Digit = 30 + 2 = 32
    
Iteration 3:
    Last_Digit = N % 10 = 1
    N = N / 10 = 0
    R = (R * 10) + Last_Digit = 320 + 1 = 321
    
Iteration 4:
    N == 0; STOP;


Time & Space Complexity:

Time Complexity: O(N), N is the number of digits
Space Complexity: O(1)


Solution:


Code in C++