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

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

    A more efficient implementation might be something like this:

    char nthdigit(int x, int n)
    {
        while (n--) {
            x /= 10;
        }
        return (x % 10) + '0';
    }
    

    This saves the effort of converting all digits to string format if you only want one of them. And, you don't have to allocate space for the converted string.

    If speed is a concern, you could precalculate an array of powers of 10 and use n to index into this array:

    char nthdigit(int x, int n)
    {
        static int powersof10[] = {1, 10, 100, 1000, ...};
        return ((x / powersof10[n]) % 10) + '0';
    }
    

    As mentioned by others, this is as close as you are going to get to bitwise operations for base 10.

提交回复
热议问题