eli5: Extracting the Kth digit from a number

298 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

Dividing by 10 without remainder cuts off the rightmost digit. Try it yourself.

The operation %10 means dividing by 10 and keeping only the remainder. The remainder of division by 10 is always the rightmost digit in the number.

So you divide by 10 repeatedly until the rightmost digit is the one you want, then you do %10 to get that digit.

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