Article 94 - How to Get a Specific Digit of an Integer?

Getting a particular digit in some specified place value of an integer may seem like a difficult task but the algorithm is quite simple.

Let us use an example, consider the integer 12345678. The digit at the ones place value, is 8 and the digit at the tens place value is 7.

While, this is rather easy by human computation, converting the idea to a computer algorithm is less trivial.

When we pick out the digit at a certain place value, we filtered out the other digits. A simpler idea is counting from the ones place value until we reach the digit that we want. This gives us the following algorithm.

Picking out a the digit at a specific place value.

int getDigitAt( int number, unsigned int place ){
    for( int i = 1; i < place; i++ ){
        number /= 10;
    }

    return number % 10;
}

Comments (0)

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2023. Vantasy World is a project developed by Vantasy Online. Privacy Policy.