How to get the Nth digit of an integer with bit-wise operations?

后端 未结 12 1155
深忆病人
深忆病人 2021-01-30 21:23

Example. 123456, and we want the third from the right (\'4\') out.

The idea in practise is to access each digit seperately (ie. 6 5 4 3 2 1).

C/C++/C# preferred.

12条回答
  •  我在风中等你
    2021-01-30 21:57

    This works for unsigned ints up to 451069, as explained here:

    def hundreds_digit(u): return mod10(div100(u))
    
    def div100(u): return div10(div10(u))
    def mod10(u):  return u - mul10(div10(u))
    def mul10(u):  return ((u << 2) + u) << 1
    
    def div10(u):
        Q = ((u >> 1) + u) >> 1  # Q = u*0.11
        Q = ((Q >> 4) + Q)       # Q = u*0.110011
        Q = ((Q >> 8) + Q) >> 3  # Q = u*0.00011001100110011
        return Q
    
    # Alternatively:
    #   def div100(u): return (u * 0xa3d7) >> 22
    # though that'd only work for 16-bit u values.
    # Or you could construct shifts and adds along the lines of div10(),
    # but I didn't go to the trouble.
    

    Testing it out:

    >>> hundreds_digit(123456)
    4
    >>> hundreds_digit(123956)
    9
    

    I'd be surprised if it's faster, though. Maybe you should reconsider your problem.

提交回复
热议问题