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

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

    Just for fun, here is the C# extension class for it:

    public static class IntExtensions
    {
        /// 
        /// Returns the nth digit from an int, 
        /// where 0 is the least significant digit 
        /// and n is the most significant digit.
        /// 
        public static int GetDigit(this int number, int digit)
        {
            for (int i = 0; i < digit; i++)
            {
                number /= 10;
            }
            return number % 10;
        }
    }
    

    Usage:

    int myNumber = 12345;
    int five = myNumber.GetDigit(0);
    int four = myNumber.GetDigit(1);
    int three = myNumber.GetDigit(2);
    int two = myNumber.GetDigit(3);
    int one = myNumber.GetDigit(4);
    int zero = myNumber.GetDigit(5);
    

提交回复
热议问题