FOR FREE MATERIALS

Number Reverse

Back to Programming

Description

The program is written here to reverse a given number. 

  • First, the number is taken as input. 
  • Using the modulus operator each time the last digit of the number at that moment is taken out and appended to the new number in reverse order. 
  • The number is now gets divided by 10 so that the last digit is cut. 

The process is continued till the original number becomes 0.

For example, if a given number is 1234 then the reverse of this number is 4321.

Algorithm

INPUT: A number

OUTPUT: The reverse of the number.

Step 1: [taking the input]

               Read n [the number to be reversed]

Step 2: [reversing the number]

               Set rev<-0

               While n>0 repeat

                              Set rev<-rev*10+(n mod 10)

                              Set n<-n/10

               [End of ‘while’ loop]

Step 3: Print “The reverse of the number is: rev”

Step 4: Stop.

Code

TIME COMPLEXITY:

while(n>0)----------------------------------O(m)

               {

                              rev=rev*10+(n%10);

                              n=n/10;

               }

The time complexity is O(m) where ‘m’ is the number of digits of the given input. 

The time complexity can also be represented as O(log10n) where n is the given input. There is almost log10n number of digits in a number n.

SPACE COMPLEXITY:

The space complexity of this program is O(1) as it requires a constant number of memory spaces to execute the program for any given input.