table of Contents
Note: The original is not easy, reproduced, please be sure to indicate the source and author, thanks for the support!
How to get a long integer integer after reverse
Recently I encountered such a problem in writing code: How to get to get a long integer after a long integer number in reverse order? Such as input \ (A = 12345678 \) , to obtain an output \ (RA = 87654321 \) .
Below, a careful analysis of the characteristics of the number of input, you can get a simple recursive algorithm to solve this problem.
Note: The final countdown time to make plans less the second line plus
void reverse(unsigned long a, unsigned long *sum, unsigned long power)
{
if (a > 10)
reverse(a/10, sum, power/10);
*sum += (a % 10) * power;
}
unsigned long get_reverse(unsigned long a)
{
/* 根据a的位数确定最大位权值 */
int i;
unsigned long power = 1;
char buf[16];
sprintf(buf, "%lu", a);
for (i = 0; i < strlen(buf) - 1; i++)
power *= 10;
/* 调用reverse() */
unsigned long sum = 0;
reverse(a, &sum, power);
return sum;
}
Want to come back to the above code, you will find now borrow sprintf () can easily be \ (a \) the maximum bit weight calculated, then why this inefficiency is also recursive calculation with the use of it? Thus, a little better efficiency, avoid recursive algorithm can be implemented as follows.
unsigned long get_reverse(unsigned long a)
{
/* 根据a的位数确定最大位权值 */
int i;
unsigned long power = 1;
char buf[16];
sprintf(buf, "%lu", a);
for (i = 0; i < strlen(buf) - 1; i++)
power *= 10;
unsigned long sum = 0;
for (i = strlen(buf) - 1; i >= 0; i--)
{
sum += (buf[i] - '0') * power;
power /= 10;
}
return sum;
}
To the complexity of the code is: \ (O (strlen (A)) = O (log ~ A) \) . Furthermore, there is no more efficient algorithm to solve this problem?