Visual C++ - Reverse Number
I have given here Visual C++ code to reverse a given number. It counts the digits and then it uses / and % operators and simple multiplication to reverse the number.
Source Code
#include <stdio.h>
#include <conio.h>
#include <math.h>
int CountNumberOfDigits_usingLog(int n)
{
return (int) (log10((double)n) + 1);
}
int CountNumberOfDigits(int n)
{
int numdgits = 0;
do
{
n = n / 10;
numdgits++;
} while(n > 0);
return numdgits;
}
void main()
{
int i, n, number, numdigits, result;
printf("\nProgram to find the reverse of a number. Enter -1 to exit");
while(1)
{
printf("\nEnter a number: ");
scanf("%d", &number);
if(number < 0)
break;
n = number;
numdigits = CountNumberOfDigits(number);
printf("\nNumber of digits in %d is: %d\n", number, numdigits);
result = 0;
for(i = 0; i < numdigits; i++)
{
result *= 10;
result += n % 10;
n = n / 10;
}
printf("The reverse of number %d is : %d\n", number, result);
}
}
Output
|