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

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

    In C you could do something like the following, where n=0 would indicate the rightmost digit

    char nthDigitFromRight(int x,int n)
    {
        char str[20];
        sprintf(str,"%020d",x);
        return(str[19 - x]);
    }
    

    Change [19-x] to [20-x] if you want n=1 for rightmost digit.

提交回复
热议问题