eli5: Extracting the Kth digit from a number

300 views

I recently read that this formula,

(Number / 10^K-1) % 10
Edit: updated formula to use K-1

Will give me the Kth digit of Number.

For example if i want the 2nd digit from 345, I have (345/100)%10 which gives 4.

Why does this work? 🤔

In: 3

5 Answers

Anonymous 0 Comments

Two parts:

Dividing a number by 10 shoves its least significant digit (rightmost digit) past the decimal. 1842/10 = 184.2. You’ve just pushed 2 past the decimal, so the new number prior to the decimal is 4. If you want a number further up the chain, you keep dividing by 10. 184.2/10=18.42. 8 is the new unitary number. You’ve “selected” the 3rd number by dividing by 10 twice. Number / 10^(k-1).

Taking the remainder of the division by 10 simply eliminates the rest of the digits, leaving the one you’ve selected. 18.42%10=8.4 . Technically, you would also want to get rid of the decimal part, so you would take the floor of said number. floor(8.4)=8.

You are viewing 1 out of 5 answers, click here to view all answers.