As nothing in the question says that the result must still be an integer, why not make it an array instead? That would also elegantly solve the problem that an input that ends with a "0" would be chopped... or, even better, don't use any return value. After all, you did not ask for one.
#include <stdio.h>
voidreverse_int(intin){while(in>0){printf("%d",in%10);/* modulo 10 ... */in/=10;/* ... and move one digit. */}}/* PoC: */intmain(void){reverse_int(1234567890);return0;}
Wednesday
Write a program to reverse the digits of a positive integer but without converting it to a string.
probably not the best solution but it works. (unless you want leading zeros...but I'm assuming that's not the case since it wants a number).
As nothing in the question says that the result must still be an integer, why not make it an array instead? That would also elegantly solve the problem that an input that ends with a "0" would be chopped... or, even better, don't use any return value. After all, you did not ask for one.
Output:
F#
while
loop on compile)i % 10
gets the right-most digit ofi
rev * 10
shifts the numbers left, with right-most zeroi / 10
shifts the numbers right, dropping right-most digitI happened to remember these little number tricks from a previous challenge. This is basically using integers as digit stacks.
Thank you, Ali.
This has been one of the most fun challenges.
Took me awhile but here is the C# version.
The gist is that, remainder is calculated for each digit, stored in a stack (LIFO - last in first out) to reverse the remainder.
Lastly the
total
is reconstructed from the stack.Runnable code on .NET Fiddle
Oh that's a really cool approach!
My Python solution:
And now this is... 😮
... broken.
You did not pass.
987654321
is how I expect it to work though without the 0 in the beginning as you should return apositive integer
.That was not a part of the question, so I would say that the result should still start with a 0.
the positive integer shouldn't have a leading zero I don't think. It's at least up to interpretation.