Reverse a number

Reverse a number


Given a number, we need to reverse it.

Reversing the number means reversing the digits of the number. For example, if the number is 12345 then the output should be 54321.

Logic

  1. Get the number from the user and store it as n.
  2. Initialize a variable rev with 0 to store the reversed number.
  3. Start a while loop checking whether the n != 0(if n is 0 exit the while loop).
  4. Multiply the rev by 10 and add the remainder of n when divided by 10 to rev. That is rev = rev * 10 + n % 10.
  5. Divide n by 10 and store it back to n. That is n = n / 10.
  6. Repeat the steps 3, 4 and 5 till n != 0.
  7. Print the value of rev.

Flowchart

Reverse a number flow chart

Pseudocode

BEGIN
    INPUT n
    rev = 0
    WHILE n != 0
        rev = rev * 10 + n % 10
        n = n / 10
    ENDWHILE
    OUTPUT rev
END

Implementation

C

#include <stdio.h>

int reverse_number(int n)
{
    int rev = 0;
    while (n != 0)
    {
        rev = rev * 10 + n % 10;
        n = n / 10;
    }
    return rev;
}

int main()
{
    int n, rev = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    rev = reverse_number(n);
    printf("Reversed number: %d", rev);
    return 0;
}

Python

def reverse_number(n):
    rev = 0
    while n != 0:
        rev = rev * 10 + n % 10
        n = n // 10
    return rev

n = int(input("Enter a number: "))
rev = reverse_number(n)
print("Reversed number:", rev)