The most efficient way to reverse a number

后端 未结 10 821

I am looking for an efficient algorithm to reverse a number, e.g.

Input: 3456789

Output: 9876543

In C++ there are p

10条回答
  •  轮回少年
    2021-01-13 05:22

    If it is 32-bit unsigned integer (987,654,321 being max input) and if you have 4GB free memory(by efficiency, did you mean memory too?),

    result=table[value]; // index 12345 has 54321, index 123 has 321
    

    should be fast enough. Assuming memory is accessed at 100 ns time or 200 cycles and integer is 7 digits on average, other solutions have these:

    • 7 multiplications,
    • 7 adds,
    • 7 modulo,
    • 7 divisions,
    • 7 loop iterations with 7 comparisons

    if these make more than 100 nanoseconds / 200 cycles, then table would be faster. For example, 1 integer division can be as high as 40 cycles, so I guess this can be fast enough. If inputs are repeated, then data will coming from cache will have even less latency.

    But if there are millions of reversing operations in parallel, then computing by CPU is absolutely the better choice (probably 30x-100x speedup using vectorized compute loop + multithreading) than accessing table. It has multiple pipelines per core and multiple cores. You can even choose CUDA/OpenCL with a GPU for extra throughput and this reversing solution from other answers look like perfectly embarrassingly parallelizable since 1 input computes independently of other inputs.

提交回复
热议问题