Quickest Method to Reverse in String in C#.net

前端 未结 11 1901
庸人自扰
庸人自扰 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 18:59

    A you want to compare a number with its reverse it may be faster to reverse the number using division rather than converting it to a string. I still need to test the speed of it.

     private static int Reverse(int num) {
         int res = 0;
         while (num > 0) {
            int rm ;
            num = Math.DivRem(num, 10, out rm);
            res = res * 10 + rm;
         }
         return res;
      }
    

    EDIT: DivRem was about 1% faster than division and module in my computer. A speed optimization is exit if the last digit is 0:

      private static int Reverse(int num) {
         int res = 0;
         int rm;
         num = Math.DivRem(num, 10, out rm);
         //Some magic value or return false, see below.
         if (rm == 0) return -1 ; 
         res = res * 10 + rm;
         while (num > 0) {
            num = Math.DivRem(num, 10, out rm);
            res = res * 10 + rm;
         }
         return res ;
      }
    

    Making the method return a bool was slightly slower than comparing to a bool in a loop in my computer, but I don't understand why. Please test in your computer.

    Multiplication and bit-shifing should be faster than division but probably are not precise enough. EDIT: using long seems be precise enough.

      private static int FastReverse(int num) {
         int res = 0;
         int q = (int)((214748365L * num) >> 31);
         int rm = num - 10 * q;
         num = q;
         if (rm == 0) return -1;
         res = res * 10 + rm;
         while (num > 0) {
            q = (int)((214748365L * num) >> 31);
            rm = num - 10 * q;
            num = q;
            res = res * 10 + rm;
         }
         return res;
      }
    

    (214748365L * num) >> 31 is equal to i / 10 until 1,073,741,829 where 1 / 10 gives 107374182 and the multiplication + binary shifting gives 107374183.

提交回复
热议问题