Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the seventh digit from an integer

I have a integer of 10 digits. I need to get the 7th digit of that integer.

I have found a mathematical solution to get the first digit of an integer.

var myDigit = 2345346792;

var firstDigit = Math.Abs(myDigit);
while (firstDigit >= 10)
{
     firstDigit /= 10;
}

How can I get the seventh digit from myDigit? I am trying to avoid casting to string and doing a substring. I would like to see the mathemathical version of getting the seventh digit.

Anyone?

like image 563
codingjoe Avatar asked Dec 06 '12 21:12

codingjoe


7 Answers

var seventh_digit = ( myDigit/1000000 ) % 10;
like image 94
Mohammad Jafar Mashhadi Avatar answered Nov 08 '22 13:11

Mohammad Jafar Mashhadi


int getSeventhDigit(int number)
{
    while(number >= 10000000)
        number /= 10;

    return number % 10;
}

This will take the last digit of numbers with 7 or less digits.

For numbers with 8 or more digits, it will divide by 10 until the number is 7 digits long, then take the last digit.

like image 43
David Yaw Avatar answered Nov 08 '22 13:11

David Yaw


Mathematical solution without while loops:

int myDigit = 2345346792;

var seventh = (myDigit / 1000000) % 10;

//result should be 5, your seventh digit from the right
like image 34
Roast Avatar answered Nov 08 '22 12:11

Roast


More generally, you can create a (zero-based) array from the digits:

uint myDigit = 2345346792;

int[] digits = new int[10];
for (int i = 9; i >= 0; i--)
{
    digits[i] = (int)(myDigit % 10);
    myDigit /= 10;
}

That should be useful for whatever manipulation you wish to do.

like image 32
Matthew Strawbridge Avatar answered Nov 08 '22 14:11

Matthew Strawbridge


var nthDigit = (int)((number / Math.Pow(10, nth - 1)) % 10);

Where nth is n-th digit of the number.

like image 37
Aleksandar Toplek Avatar answered Nov 08 '22 12:11

Aleksandar Toplek


Assuming that the "zeroth digit" is the least significant digit, this should do you:

    public static int nthDigit( int value , int n )
    {
        if ( n < 0 ) throw new ArgumentException();
        if ( value < 0 ) throw new ArgumentException() ;

        while ( n-- > 0 )
        {
            value /= 10 ;
        }

        int digit = value % 10 ;
        return digit ;
    }
like image 23
Nicholas Carey Avatar answered Nov 08 '22 13:11

Nicholas Carey


Something like this (C code, but should be readily portable):

if (n < 1000000)
  return 0;        // no 7th digit
while (n > 9999999)
  n /= 10;         // now in the range [1,000,000..9,999,999]
return n % 10;
like image 28
twalberg Avatar answered Nov 08 '22 12:11

twalberg