Leetcode

Count Good Numbers

  • Time:O(\log n)
  • Space:O(\log n)

C++

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);
  }
};

JAVA

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);
  }
}

Python

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