Skip to content

1922. Count Good Numbers

  • Time: $O(\log n)$
  • Space: $O(\log n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int countGoodNumbers(long long n) {
    return myPow(4 * 5, n / 2) * (n & 1 ? 5 : 1) % kMod;
  }

 private:
  constexpr static int kMod = 1e9 + 7;

  long myPow(long x, long n) {
    if (n == 0)
      return 1;
    if (n & 1)
      return x * myPow(x, n - 1) % kMod;
    return myPow(x * x % kMod, n / 2);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int countGoodNumbers(long n) {
    return (int) (myPow(4 * 5, n / 2) * (n % 2 == 1 ? 5 : 1) % kMod);
  }

  private static final int kMod = (int) 1e9 + 7;

  private long myPow(long x, long n) {
    if (n == 0)
      return 1;
    if (n % 2 == 1)
      return x * myPow(x, n - 1) % kMod;
    return myPow(x * x % kMod, n / 2);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def countGoodNumbers(self, n: int) -> int:
    kMod = int(1e9) + 7

    def myPow(x: int, n: int) -> int:
      if n == 0:
        return 1
      if n & 1:
        return x * myPow(x, n - 1) % kMod
      return myPow(x * x % kMod, n // 2)

    return myPow(4 * 5, n // 2) * (5 if n & 1 else 1) % kMod
Back to top