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
- Get the number from the user and store it as
n
. - Initialize a variable
rev
with0
to store the reversed number. - Start a while loop checking whether the
n != 0
(ifn
is0
exit the while loop). - Multiply the
rev
by10
and add the remainder ofn
when divided by10
torev
. That isrev = rev * 10 + n % 10
. - Divide
n
by10
and store it back ton
. That isn = n / 10
. - Repeat the steps 3, 4 and 5 till
n != 0
. - Print the value of
rev
.
Flowchart
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)