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

后端 未结 12 1035
深忆病人
深忆病人 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:55

    value = (number % (10^position)) / 10^(position - 1)

    Example:

    number = 23846

    position = 1 -> value = 6

    position = 2 -> value = 4

    position = 3 -> value = 8

    Here is a simple Objective-C utility method to do this:

    + (int)digitAtPosition:(int)pos of:(int)number {
    
        return (number % ((int)pow(10, pos))) / (int)pow(10, pos - 1);
    }
    

提交回复
热议问题