# Reversing an Integer Number Along With C Program

Reversing an Integer Number

To reverse an integer number, it is divided by 10, the remainder is pushed to the stack and the quotient is again divided by 10. On every division, the remainder is pushed to the stack and the quotient is re-divided by 10. The process continues until the quotient becomes less than 10. When the quotient becomes less than 10, that quotient too is pushed to stack.

For example, let us assume that we want to reverse 724. Number 724 is divided by 10, quotient will be 72 and remainder will be 4. The remainder 4 is pushed to stack (it will be stored at top=0) i.e. at location stack (see Figure 1). The quotient 72 is again divided by 10, the quotient will be 7 and remainder will be 2. The remainder 2 is pushed to stack (at top=1) i.e. at stack location. Because, the quotient 7 is less than 10, it can’t be divided by 10 and is pushed to stack at top=2 location i.e. at stack location. Figure 1 – Dividing integer number by 10 and pushing the remainders into stack

All, the remainders that are in stack are popped out in LIFO order that is Last In First Out. The numbers popped from stack will be 7, 2 and 4. To reverse the integer value, every digit is multiplied by 10 to the power of a superscript. The value of superscript begins with 0 for the right most digit and is incremented by 1 on moving left. Like, 7 (the right most binary digit is multiplied by 100, 2 i.e. the digit on left of 7 is multiplied by 101, the next digit to left i.e. 4 is multiplied by 102.

The result of each multiplication is then added to get the reverse integer value. The entire procedure is explained in Figure 2. Figure 2 – Popping numbers from stack and multiplying by powers of 10 to get reverse integer

C Program to reverse an integer value

# include <stdio.h>

# include <math.h>

#define max 10

/* You can increase the array size to a bigger number if you think user can enter a very large binary value */

int top=-1;

int stack[max];

main()

{

int j, numb, remainder, temp, revnumb=0, power=0;

printf(“Enter a number “);

scanf(“%d”,&numb);

/* If you want to enable the user to enter value bigger than 32,767 (its a limit of an int type), use long int i.e. replace %d by %ld. With long integer, user can enter a value between -2,147,483,647 to 2,147,483,647 */

temp=numb;

while(numb >0)

{

remainder=numb%10;

push(remainder);

numb=numb/10;

}

printf(“The reverse of the number %d is “, temp);

while(top >=0)

{

j=pop();

revnumb=revnumb+j*pow(10,power);

power++;

}

printf(“%d”, revnumb);

}

push(int m)

{

top++;

stack[top]=m;

}

int pop()

{

int j;

if(top==-1)return(top);

else

{

j=stack[top];

top–;

return(j);

}

}