| 2 | |
| 3 | public class Question { |
| 4 | public static int count2sInRangeAtDigit(int number, int d) { |
| 5 | int powerOf10 = (int) Math.pow(10, d); |
| 6 | int nextPowerOf10 = powerOf10 * 10; |
| 7 | int right = number % powerOf10; |
| 8 | |
| 9 | int roundDown = number - number % nextPowerOf10; |
| 10 | int roundUp = roundDown + nextPowerOf10; |
| 11 | |
| 12 | int digit = (number / powerOf10) % 10; |
| 13 | if (digit < 2) { // if the digit in spot digit is |
| 14 | return roundDown / 10; |
| 15 | } else if (digit == 2) { |
| 16 | return roundDown / 10 + right + 1; |
| 17 | } else { |
| 18 | return roundUp / 10; |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | public static int count2sInRange(int number) { |
| 23 | int count = 0; |