Leetcode

Super Pow

  • Time:O(n)
  • Space:O(1)

C++

class Solution {
 public:
  int superPow(int a, vector<int>& b) {
    constexpr int k = 1337;
    int ans = 1;

    auto powMod = [&](int x, int y) {  // x^y % k
      int pow = 1;
      while (y--)
        pow = (pow * x) % k;
      return pow;
    };

    a %= k;
    for (const int i : b)
      ans = powMod(ans, 10) * powMod(a, i) % k;

    return ans;
  }
};

JAVA

class Solution {
  public int superPow(int a, int[] b) {
    int ans = 1;

    a %= k;
    for (final int i : b)
      ans = powMod(ans, 10) * powMod(a, i) % k;

    return ans;
  }

  private final int k = 1337;

  private int powMod(int x, int y) {
    int pow = 1;
    while (y-- > 0)
      pow = (pow * x) % k;
    return pow;
  }
}

Python

class Solution:
  def superPow(self, a: int, b: List[int]) -> int:
    def powMod(x: int, y: int) -> int:
      pow = 1
      for _ in range(y):
        pow = (pow * x) % k
      return pow

    k = 1337
    ans = 1

    for i in b:
      ans = powMod(ans, 10) * powMod(a, i) % k

    return ans