I’m currently writing a quick solution for Euler Problem #4 where one must find the largest palindromic number from the product of two 3-digit numbers.
To identify if a number is palindromic, you would obviously compare a reverse of the number with the original.
Since C# doesn’t have a built in String.Reverse() method, what is the quickest way to reverse a string?
I will be testing all the suggested solution in a loop with 100,000,000 iterations. The correct answer will be given to the person who submitted the fastest solution.
I will be testing the solution in a C#.Net 3.5 console application
I think it might be faster to do the comparison in-place. If you reverse the string, you’ve got to:
If you perform the comparison in place, you do only the last step. An even then, your comparison is only half the string (or half – 0.5, in the event of an odd number of characters). Something like the following should work:
EDIT:
Although this answers the OP’s question, the solutions offered by ggf31416 and configurator solve the OP’s real need about 30% faster, by my tests. configurator’s solution is a tiny bit faster than ggf31416’s, if you convert it to a static method and use
ints instead ofulongs (but much slower, otherwise).Incidentally, running through these examples to solve the problem the OP mentions (finding the largest palindromic product of any two three-digit numbers) with the simple (perhaps naïve) loop below:
yields the following results on my machine:
Each produces the correct result of
913 * 993 = 906609.