eli5: Extracting the Kth digit from a number

296 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

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.

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