MCPcopy
hub / github.com/careercup/ctci / count2sInRangeAtDigit

Method count2sInRangeAtDigit

java/Chapter 18/Question18_4/Question.java:4–20  ·  view source on GitHub ↗
(int number, int d)

Source from the content-addressed store, hash-verified

2
3public 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;

Callers 1

count2sInRangeMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected