static long ReverseString(long number)
{
char[] str = number.ToString().ToCharArray();
Array.Reverse(str);
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.
Conclusion:
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.