It really does not matter how many digits there are, the principal is exactly the same. The following function is the most efficient way to reverse any whole number in the range -2,147,483,648 to 2,147,483,647, inclusive (assuming a 32-bit integer). To increase the range, create separate functions to cater for 64-bit and 128-bit integers. Converting the number to a string and reversing the string is also an option (see previous answer, below), however it is by far the least efficient method of reversing a whole number.
int RevNum( int num )
{
const int base = 10;
int remain = 0;
int result = 0;
do
{
remain = num % base;
result *= base;
result += remain;
} while( num /= base);
return( result );
}
Previous AnswerThis is assuming the number is decimal.
There are several approaches to the problem, depending on the resources you have available or wish to use to solve it.
One way to achieve this is to isolate the digits through modulo division and the remultiply them in the desired order:
rev = ((original % 10) * 10000) + (((original / 10) % 10) * 1000) + (((original / 100) % 10) * 100) + (((original / 1000) % 10) * 10) + (original / 10000);
An alternative that doesn't look so messy:
int temp = original;
int rev = 0;
for (int i=0;i<5;i++)
{
rev = (rev * 10) + (temp % 10);
temp /= 10;
}
If you're employing strings, then another novel way can be used.
#include
#include
#include
char numstring[6];
snprintf(numstring,5,"%d",original);
strrev(numstring);
rev = atoi(numstring);
Note that these are just examples of how it can be achieved. There is no standard function to reverse a decimal number in C or C++, so it's up to you to find or code a solution for yourself.
It doesn't matter how many digits are involved, the principal is the same.
int RevNum( int num )
{
const int base = 10;
int result = 0;
int remain = 0;
do
{
remain = num % base;
result *= base;
result += remain;
} while( num /= base);
return( result );
}
44444
00000
21978
99324 (the third digit is 3)3+2=5
try 91511, 9+5=14
23
The number is 21978. 21978 when multiplied by 4 which gives the result 87912 which is in reverse order.
main() { int no,reverse=0,digit; scanf("%d",no); for( ;no>0; ) { digit=no%10; reverse=reverse*10 + digit; no=no/10; } printf("%d",reverse); }
105 - is the smallest tree-digit number that has the digit 5
Any number that ends with the digit 5 is divisible by 5.Any number that ends with the digit 5 is divisible by 5.Any number that ends with the digit 5 is divisible by 5.Any number that ends with the digit 5 is divisible by 5.
The commutative property of addition states that a number plus another number equals the same number plus the same number in reverse order. An example of this is 2+5=5+3.
The smallest, positive 5-digit whole number is 10,000