Quickest Method to Reverse in String in C#.net

前端 未结 11 1921
庸人自扰
庸人自扰 2021-02-02 18:17

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

11条回答
  •  滥情空心
    2021-02-02 19:01

    I think it might be faster to do the comparison in-place. If you reverse the string, you've got to:

    1. Instantiate a new string object (or StringBuffer object)
    2. Copy the data (in reverse) from the first string to the new string
    3. Do your comparison.

    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;
    }
    

    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 of ulongs (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:

    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.
    

    Each produces the correct result of 913 * 993 = 906609.

提交回复
热议问题