最快的方法在字符串反向用C#.net [英] Quickest Method to Reverse in String in C#.net
问题描述
我目前正在写的欧拉问题#4的快速解决方案,其中一个必须找到两个3位数字的产品最大的回文数。
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.
<强>由于C#不具有内置String.Reverse ()方法,什么是扭转一个字符串的最快方法是什么?
的我将与亿itterations来测试所有建议的解决方案,在一个循环。正确答案将给予谁提交的最快的解决方案的人。的
的我将测试在C#.NET 3.5的控制台解决方案应用的
推荐答案
我觉得这可能会更快做的地方进行比较。如果颠倒字符串,你就必须:
I think it might be faster to do the comparison in-place. If you reverse the string, you've got to:
- 实例化一个新的字符串对象(或StringBuffer对象)
- 从第一个字符串复制数据(反向),以新的字符串
- 请您比较。
如果您执行到位的比较,你能做的只有最后一步。一个即使是这样,你的比较是只有一半的字符串(或半 - 0.5,在奇数个字符的事件)。像下面这样的东西应该工作:
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:
static bool IsPalindromic(string s){
int len = s.Length;
int half = len-- >> 1;
for(int i = 0; i < half; i++)
if(s[i] != s[len - i])
return false;
return true;
}
编辑:
虽然这个回答OP的问题,通过的 ggf31416 和的配置解决了OP的实际需求约30%的速度,在我的测试。配置的解决方案比ggf31416的一点点快,如果你把它转换为静态方法,并使用 INT
的S代替 ULONG
S(但相对很慢,其他)。
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 int
s instead of ulong
s (but much slower, otherwise).
顺便说一下,通过这些实例来运行解决下面的简单(也许是幼稚)循环的OP提到这个问题(发现任何两个三位数字的最大回文产品):
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:
for(int i = 100; i < 1000; i++)
for(int j = i; j < 1000; j++) // calculations where j < i would be redundant
...
得到我的机器上,结果如下:
yields the following results on my machine:
IsPalindromic(product.ToString()) took 0.3064174 seconds.
ggf31416Reverse(product) == product took 0.1933994 seconds.
configuratorReverse(product) == product took 0.1872061 seconds.
每个产生正确的结果 913 * 993 = 906609
。
这篇关于最快的方法在字符串反向用C#.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!