# Write a C program to reverse digits of a number

ITERATIVE WAY
Algorithm:

```Input:  num
(1) Initialize rev_num = 0
(2) Loop while num > 0
(a) Multiply rev_num by 10 and add remainder of num
divide by 10 to rev_num
rev_num = rev_num*10 + num%10;
(b) Divide num by 10
(3) Return rev_num
```

Example:
num = 4562
rev_num = 0

rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456

rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45

rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4

rev_num = rev_num *10 + num%10 = 265 + 4 = 2654
num = num/10 = 0

Program:

```#include <stdio.h>

/* Iterative function to reverse digits of num*/
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}

/*Driver program to test reversDigits*/
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));

getchar();
return 0;
}
```

Time Complexity: O(Log(n)) where n is the input number.

```
```

RECURSIVE WAY
Thanks to Raj for adding this to the original post.

```#include <stdio.h>;

/* Recursive function to reverse digits of num*/
int reversDigits(int num)
{
static int rev_num = 0;
static int base_pos = 1;
if(num > 0)
{
reversDigits(num/10);
rev_num  += (num%10)*base_pos;
base_pos *= 10;
}
return rev_num;
}

/*Driver program to test reversDigits*/
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));

getchar();
return 0;
}
```

Time Complexity: O(Log(n)) where n is the input number

Note that above above program doesn’t consider leading zeroes. For example, for 100 program will print 1. If you want to print 001 then see this comment from Maheshwar.

Try extensions of above functions that should also work for floating point numbers.

• gowthami

• Anant

Something below can also work

// ***** Print reverse of a digit eg: 2345.

#include

using namespace std;

{

static int i = 0;

while (i != val)

{

i++;

}

cout << *a;

}

int _tmain(int argc, _TCHAR* argv[])

{

int a[4] = {2,3,4,5};

getchar ();

return 0;

}

• Peter

Hey there!! I might sound stupid, but, I had a kinda doubt….

I wrote this code and the output for any 4 digit int is correct… however, (my doubt) any number more than 5 digit is stored correctly in num but rev is f’d up…. pls help me clear my mind…. I do know that the range for long int is -2,147,483,648 -> +2,147,483,647……

#include

#include

void main()

{

clrscr();

long int num, temp, i, rev=0;

printf(“nnEnter any number: “);

scanf(“%d”, &num);

temp = num;

do

{

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

temp /= 10;

}while(temp != 0);

printf(“nnThe reverse of ‘%d’ is ‘%d'”, num, rev);

getch();

}

• Rishikesh

I tried another simple logic for reversing digits in C#, but when I try to compile it, my PC gives me some errors, saying that “Function call missing” in lines 10 and 12. Could you pls tell me where I went wrong?

``` #include #include main() { int a,b,c; clrscr(); printf("enter the number"); scanf("%d",( (a*100) + (b*10) + c ); printf("The reversed number is %d", ( (c*100) + (b*10) + a ); getch(); return 0; ```

`}`

• diwakarreddy

thanks bayya it is very helpful for me

• Brian

Recursive method

``` public static int recurseReverse(int prefixNumber, int m){ if( m == 0) return prefixNumber; return recurseReverse(prefixNumber * 10 + m %10, m /10); } public static void main(String[] args) { int[] nums = {123,0,789,77}; for(int num: nums){ System.out.println(recurseReverse(num %10, num /10)); } } ```

• sakib

beautifull

• Unique
``` ```
//Very Simple Logic !!!
while(num>0)
{
reverse=num%10;
num=num/10;
printf("%ld",reverse);
}
``` ```
• moonlight

why the complexsity is lg(n).. doesnot it looping over the digits one by one???? so it should be o(number of digits)?

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• DMK

Yes, the complexity would be O(n) where ‘n’ is the number of digits.

• pawan

#include
main()
{
int num,rev_num;
rev_num=0;
printf(“enter the number\n”);
scanf(“%d”,&num);
while (num>0)
{
rev_num=(rev_num*10 + num%10);
num=num/10;
printf(“the rev_no %d\n”,rev_num);
}
return rev_num;
}

• Leon

#include
#include

int main()
{
int i=0,j=0,n,m;
int a[10];
clrscr();

printf(“\n\n Enter number : “);
scanf(“%d”,&n);

m=n;
while(m!=0)
{
a[i++]=m%10;
m=m/10;
}
printf(“\n\n The reverse of %d is : “,n);
for(j=0;j<i;j++)
{
printf("%d",a[j]);
}

getch();
return 0;
}

• Utsav

Excellent then rest… You provide me exetly what I was looking for… Thank You.

• Guddu sharma

This approach (Divide & conquer)takes O(log d) time where d is the number of digits.

``` ```
int revNum(int n,int d)
{
int first,last,di,dj;
if(n<10)
return n;
else
{
di=(int)pow(10,d-d/2);
first=revNum(n/di,d/2);

last=revNum(n- (n/di)*di,d-d/2);
dj=(int)pow(10,d/2);
return last*dj+first;
}

}
``` ```

Time complexity=T(d/2)+T(d/2)

Please let me know if i have mistaken something.

• kartik

The solution of recurrence T(d)=T(d/2)+T(d/2) is O(d). So time complexity of this solution is also O(d)

• amt

what about to print x = -123, return -321 ?

• Guddu sharma

This approach takes O(log d) time where d is the number of digits.

``` ```
int revNum(int n,int d)
{
int first,last,di,dj;
if(n<10)
return n;
else
{
di=(int)pow(10,d-d/2);
first=revNum(n/di,d/2);

last=revNum(n- (n/di)*di,d-d/2);
dj=(int)pow(10,d/2);
return last*dj+first;
}

}
``` ```

Please let me know if i have mistaken something.

• Guddu sharma

The above approach is based on divide & conquer.
Time complexity=T(d/2) + T(d/2)

• Naveen

wow… intresting logic 😉

• Vickey

Thanks bro…….. You saved my precious time……Thankx

• Here is another way to reverse digits of the number in 3 steps.

``` ```

printf("\nEnte the Number : ");
scanf("%d",&num1);

sprintf(str,"%d",num1);

strrev(str);

num2 = atoi(str);

``` ```
• mars

this page saved me hours of banging my head on the wall before the final exam!:) thank you!

• aks

@geeksforgeeks: In the recursive method, because Keeping the variables static, It would return correct result for the first function call alone. For the subsequent calls?

• kishore

urgent!!!.. in reversing a number. recursive function doesnt involve push n pop. my question is recursive function should always associates with push and pop. or not necessarily?? in the above prog .

• Gova

Nice program. it is useful to us.

• ``` ```
#include<stdio.h>

void main()
{
int a,d;
printf("Enter the Number= \n");
scanf("%d",&a);
printf("The reversal of the number=\n");

while(a>0)
{
d=a%10;
a=a/10;
printf("%d",d);
}

while(1);
}
``` ```
• vishal

this programme is valid for only two digit number

• nitish

yes it is for 2 digits only

• gunjan

its valid for three and four digits numbers too.bu we have to keep in mind tha range for the integers.

• Poliana

But this program does not function well if you type in a negative number.

• pavani

its a nice program

• maheshwar

instead of using the recursion use this :

``` ```
#include<stdio.h>

void reversDigits(unsigned int num)
{
int rev_num = 0,zeros=0;
while(num >0)
{
/*count trailing zeroes,
i.e., for 100 zeros will be 2*/
if(num%10==0)
{
zeros++;
num = num/10;
}
else break;
}

/* Get the reverse number */
while(num > 0)
{
rev_num = rev_num*10 + num%10 ;
num = num/10;
}

/* print leading zeroes in reverse number */
while(zeros--)
printf("0");

/* print reverse number */
printf("%d\n",rev_num);
}

int main()
{
unsigned int x = 100;
reversDigits(x);
getchar();
}
``` ```

this will print 10 as 01
100 as 001

• sandy

ther is no recursion code ah???? for i/p:100 o/p:001
|||ly i want to know whether we can have (iterative/recursion)code for i/p:001 o/p:100

• geeksforgeeks

@Arun Gupta: Thanks for writing to us. Could you please elaborate your approach with an example.

• Arun Gupta

I have arrived an one of the possible solutions that would store the resultant integer with the reversed digits.
This solution does not just ‘PRINT’ the digits in the reversed order but would actually compute the integer with digits in reverse order.

``` ```
int rev(int n, int sum=0)
{
if(n >input_num;
reversed_num=rev(input_num);
cout<<"\n\n"<<reversed_num;
return 0;
}
``` ```

I think that this is not the best of the solutions. I am still looking for a better solution to this problem.

• geeksforgeeks

@manoj: n is the input number for which we are reversing digits. We have added this to the post also.

• manoj

How come the time complexity of above solutions, both iterative and recursive, be O(logn)? What is n here? If n is number of digits in the input then time complexity can not be O(logn) because you will have to find quotient and remainder for every digit. Above solutions are O(n) time complexity solutions.
Please correct me, if I am assuming something wrong.
Thanks.

• Gaurang

Better you all use pointer with array to store new generated reverse number…it will produce proper output even with NUMBERS ENDING WITH ZERO(0) like :
120
Current output : 21
Correct output : 021

• sudheer

I am very thankful to the people who are maintaining this site.Because it has very good programming funda…..KEEP IT UP

• geeksforgeeks

@Raj: Thanks, nice solution. Your solution works fine and is a good alternative, we have added your solution to the post.

• raj

probably good program to understand recursion logic.

``` ```
int rev_num = 0;
int BasePos =1 ;
int reversDigits2(int num)
{
if(num > 0)
{
reversDigits2( num/10);
rev_num += (num%10)*BasePos ;
BasePos *=10 ;
}
return rev_num;
}
``` ```

what u say karthik …

• geeksforgeeks

We will be updating continuously with good quality Q&As. Keeping visiting the website and have fun.

• Hello. I think the article is really interesting. I am even interested in reading more. How soon will you update your blog?

• The best information i have found exactly here. Keep going Thank you