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

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

    Use base-10 math:

    class Program
    {
        static void Main(string[] args)
        {
            int x = 123456;
    
            for (int i = 1; i <= 6; i++)
            {
                Console.WriteLine(GetDigit(x, i));
            }
        }
    
        static int GetDigit(int number, int digit)
        {
            return (number / (int)Math.Pow(10, digit - 1)) % 10;
        }
    }
    

    Produces:

    6
    5
    4
    3
    2
    1
    

提交回复
热议问题