Jelajahi Sumber

#feat:leetcode p2438题题解

yangyi 2 minggu lalu
induk
melakukan
3f27f2c261
2 mengubah file dengan 85 tambahan dan 0 penghapusan
  1. 61 0
      src/leetcode/p2438/Solution.java
  2. 24 0
      src/leetcode/p2438/SolutionTest.java

+ 61 - 0
src/leetcode/p2438/Solution.java

@@ -0,0 +1,61 @@
+package leetcode.p2438;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2025/8/11 13:10
+ * @Description: https://leetcode.cn/problems/range-product-queries-of-powers/description/
+ * 2438. 二的幂数组中查询范围内的乘积
+ */
+class Solution {
+    int mod = (int)1e9 + 7;
+    BigInteger[] memory;
+    public int[] productQueries(int n, int[][] queries) {
+        int[] ans = new int[queries.length];
+        List<Long> power = getPower(n);
+
+        memory = new BigInteger[power.size()];
+        memory[0] = BigInteger.valueOf(power.get(0));
+        for (int i = 1; i < power.size(); i++) {
+            memory[i] = BigInteger.valueOf(power.get(i)).multiply(memory[i-1]);
+
+        }
+
+        for (int i = 0; i < ans.length; i++) {
+            ans[i] = query(queries[i]);
+        }
+
+        return ans;
+    }
+
+    private int query(int[] query) {
+        int left = query[0];
+        int right = query[1];
+        if(left == 0){
+            return memory[right].mod(BigInteger.valueOf(mod)).intValue();
+        }else{
+                return memory[right].divide(memory[left-1]).mod(BigInteger.valueOf(mod)).intValue();
+        }
+    }
+
+    private List<Long> getPower(int n) {
+        List<Long> list = new ArrayList<>();
+        while (n != 0){
+            long  t = 1L;
+            while(t <= n){
+                t *= 2;
+            }
+            t /= 2;
+            list.add(t);
+            n -= t;
+        }
+        Collections.reverse(list);
+        return list;
+    }
+}

+ 24 - 0
src/leetcode/p2438/SolutionTest.java

@@ -0,0 +1,24 @@
+package leetcode.p2438;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2025/8/11 13:34
+ * @Description:
+ */
+public class SolutionTest {
+
+    @Test
+    public void productQueries() {
+        Solution solution = new Solution();
+        int n = 806335498;
+        int[][] queries = {{1,2},{1,1}};
+        int[] ans = solution.productQueries(n, queries);
+        System.out.println(Arrays.toString(ans));
+    }
+}