MCPcopy Index your code
hub / github.com/careercup/ctci / count2sR

Method count2sR

java/Chapter 18/Question18_4/Question.java:31–62  ·  view source on GitHub ↗
(int n)

Source from the content-addressed store, hash-verified

29 }
30
31 public static int count2sR(int n) {
32 /* Alternate, messier, solution */
33
34 // Example: n = 513
35
36 // Base case
37 if (n == 0) {
38 return 0;
39 }
40
41 // Split apart 513 into 5 * 100 + 13.
42 // [Power = 100; First = 5; Remainder = 13]
43 int power = 1;
44 while (10 * power < n) {
45 power *= 10;
46 }
47 int first = n / power;
48 int remainder = n % power;
49
50 // Counts 2s from first digit
51 int nTwosFirst = 0;
52 if (first > 2) {
53 nTwosFirst += power;
54 } else if (first == 2) {
55 nTwosFirst += remainder + 1;
56 }
57
58 // Count 2s from all other digits
59 int nTwosOther = first * count2sR(power - 1) + count2sR(remainder);
60
61 return nTwosFirst + nTwosOther;
62 }
63
64 public static void main(String[] args) {
65 for (int i = 0; i < 10000; i++) {

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected