Page 1 of 1
Reverse a number without using strings
Posted: Sat Jul 23, 2022 5:00 am
by jacdelad
Code: Select all
Procedure RevNumber(num_in.q)
Protected num_out.q=0
While num_in<>0
num_out=num_out*10
num_out=num_out+num_in%10
num_in=num_in/10
Wend
ProcedureReturn num_out
EndProcedure
Debug RevNumber(123456789);shows 987654321
Debug RevNumber(123654789);shows 987456321
Re: Reverse a number without using strings
Posted: Sat Jul 23, 2022 5:23 am
by BarryG
Cute. No practical use though? Very slow compared to just reversing a string. Also doesn't handle numbers ending in a zero, or floats.
Code: Select all
Procedure RevNumber(num_in.q)
Protected num_out.q=0
While num_in<>0
num_out=num_out*10
num_out=num_out+Mod(num_in,10)
num_in=num_in/10
Wend
ProcedureReturn num_out
EndProcedure
DisableDebugger
test1_start.q=ElapsedMilliseconds()
For c=1 To 1000000
r=RevNumber(123456789)
Next
test1_time.q=ElapsedMilliseconds()-test1_start
n$="123456789"
test2_start.q=ElapsedMilliseconds()
For c=1 To 1000000
r$=ReverseString(n$)
Next
test2_time.q=ElapsedMilliseconds()-test2_start
EnableDebugger
Debug test1_time ; 1663 ms
Debug test2_time ; 119 ms
Re: Reverse a number without using strings
Posted: Sat Jul 23, 2022 5:29 am
by jacdelad
Interesting, I thought it would be faster than using a string, maybe Mod() is slow.
Technically the stored reverse value of a number ending with zeroes, like 1000, is correct. You just have to make sure to add the trailing zeroes when converting it to a string.
There is no real practical use, I just liked the approach. Including floats would be more complex.
Re: Reverse a number without using strings
Posted: Sat Jul 23, 2022 5:39 am
by BarryG
It's a good trick, though.
Re: Reverse a number without using strings
Posted: Sat Jul 23, 2022 7:13 am
by STARGĂ…TE
Mod(x,y) is a floating point function (for floats and doubles) and not useful for integers, try:
You have to use the equivalent integer operator %
Re: Reverse a number without using strings
Posted: Sat Jul 23, 2022 7:16 am
by jacdelad
@STARGATE: Aye great, didn't mention that it is for doubles/floats.