eli5: Extracting the Kth digit from a number

297 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

Either you start counting the first number as the 0th number or it is (k-1)

n / 10^k cuts of k numbers on the right (assuming division with round down)

and the % 10 cuts of everything left of the ones-digit

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