# eli5: Extracting the Kth digit from a number

173 views
0

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 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. Pretty sure it’s (Number / 10^K-1 ) % 10

In your example 345/100 = 3.45, and 3.45 % 10 = 3.45 (if you’re working with whole numbers when dividing it’s 3 in both cases.) 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. 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 I am pretty sure that your formula is wrong or at least wrong in how you count the digits.

it only really works if you count the digits from least significant to most significant (i.e. right to left) and start with zero.

(345 / 10^0) % 10 = 5
(345 / 10^1) % 10 = 4
(345 / 10^2) % 10 = 3

If you want to start counting the digits by one like a normal person you should use (Number / 10^(k-1)) % 10

The % sign is this case is a modulo operator. It shows you what you have left over after division using only whole numbers. For example 11%4=3 , because after dividing 11 by 4 you get 2 and 3 left over.

% 10 basically means that you take throw away any part of a number that is a multiple of ten and in base ten system this leaves you with just the least significant digit.

12345 % 10 = 5
54321 % 10 = 1
789 % 10 = 9
10000 % 10 = 0

The division by 10 to the kth power just makes sure that whatever digit you want is in the correct position for the second operation to work.