Tuesday, March 18, 2008

Reversing number in Csharp

This time i want to compare 2 methods for reversing a number. One method is based on Array.Reverse method and second - on number modulus 10 operator. Code is this for reversing number as string (C#):

static long ReverseString(long number)
char[] str = number.ToString().ToCharArray();
return long.Parse(new string(str));

And code for reversing number by math operations (C#):

static long ReverseNumber(long number)
long digit = number % 10;
long rest = (long) number / 10;
long o = digit;

while (rest > 0)
digit = rest % 10;
rest /= 10;
o = (o*10)+ digit;
return o;

And these separate functions are run for 1000000 iterations.
Then execution time is measured.
Situation is this:

Function ReverseString --> 984 ms.
Function ReverseNumber --> 765 ms.

Reversing by math operations is a bit faster- faster by factor of 1.3
So if for some reason you need to reverse a number - do it with math,
rather than by string/array operations.

No comments:

Post a Comment

Comment will be posted after comment moderation.
Thank you for your appreciation.