Skip to content

1067. Digit Count in Range

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  int digitsCount(int d, int low, int high) {
    return countDigit(high, d) - countDigit(low - 1, d);
  }

 private:
  int countDigit(int n, int d) {
    int count = 0;

    for (int pow10 = 1; pow10 <= n; pow10 *= 10) {
      const int divisor = pow10 * 10;
      const int quotient = n / divisor;
      const int remainder = n % divisor;

      if (quotient > 0)
        count += quotient * pow10;
      if (d == 0)
        count -= pow10;
      if (remainder >= d * pow10)
        count += min(remainder - d * pow10 + 1, pow10);
    }

    return count;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int digitsCount(int d, int low, int high) {
    return countDigit(high, d) - countDigit(low - 1, d);
  }

  private int countDigit(int n, int d) {
    int count = 0;

    for (int pow10 = 1; pow10 <= n; pow10 *= 10) {
      final int divisor = pow10 * 10;
      final int quotient = n / divisor;
      final int remainder = n % divisor;

      if (quotient > 0)
        count += quotient * pow10;
      if (d == 0)
        count -= pow10;
      if (remainder >= d * pow10)
        count += Math.min(remainder - d * pow10 + 1, pow10);
    }

    return count;
  }
}