How many $2$'s are there between $1$ and $1000?$

1.5k Views Asked by At

The following is an interview question.

Question: How many $2$'s are there between $1$ and $1000?$

For example, there are one copy of $2$ between $1$ and $10$ and $20$ copies of $2$'s between $1$ and $100.$

I calculated the above using brute-force. I think there should be an easier way to do this for large number such as $1000.$

2

There are 2 best solutions below

2
On BEST ANSWER

If you prefix the numbers with $0$s so that they are all three digits, you can ask the number of $2$s in the range $000$ to $999$. You should be able to convince yourself that the digits are equally distributed in this range. There are $3000$ digits, so $300\ 2$s. Deleting $000$ and adding $1000$ does not change the result.

2
On

First calculate the number of $2$'s in unit digits. There are $10$ such up to hundred and $100$ such $2's$ up to $1000$.

Then calculate all $2's$ in tens place. $10$ such up to hundred and $100$ up to $1000$.

Then calculate all $2's$ in hundreds place. $0$ such up to hundred and $100$ up to $1000$.

Therefore, total number of $2's$ are $20$ up to $100$ and $300$ up to one thousand.