Ver Fonte

#feat:leetcode p1545题题解

yangyi há 2 semanas atrás
pai
commit
ceecdc9eae
2 ficheiros alterados com 71 adições e 0 exclusões
  1. 39 0
      src/leetcode/p1545/Solution.java
  2. 32 0
      src/leetcode/p1545/SolutionTest.java

+ 39 - 0
src/leetcode/p1545/Solution.java

@@ -0,0 +1,39 @@
+package leetcode.p1545;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/3 18:46
+ * @Description: https://leetcode.cn/problems/find-kth-bit-in-nth-binary-string/description/
+ * 1545. 找出第 N 个二进制字符串中的第 K 位
+ */
+public class Solution {
+    public char findKthBit(int n, int k) {
+        char result = '0';
+        StringBuilder stringBuilder = new StringBuilder("0");
+        for (int i = 1; i < n; i++) {
+            if (stringBuilder.length() >= k) {
+                break;
+            }
+            StringBuilder reverse = new StringBuilder(invert(stringBuilder.toString())).reverse();
+            stringBuilder
+                    .append('1')
+                    .append(reverse);
+        }
+        result = stringBuilder.charAt(k-1);
+        return result;
+    }
+
+    private String invert(String str) {
+        StringBuilder stringBuilder = new StringBuilder(str);
+        for (int i = 0; i < stringBuilder.length(); i++) {
+            if (stringBuilder.charAt(i) == '0') {
+                stringBuilder.setCharAt(i, '1');
+            } else {
+                stringBuilder.setCharAt(i, '0');
+            }
+        }
+        return stringBuilder.toString();
+    }
+}

+ 32 - 0
src/leetcode/p1545/SolutionTest.java

@@ -0,0 +1,32 @@
+package leetcode.p1545;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/3 18:58
+ * @Description:
+ */
+public class SolutionTest {
+
+    @Test
+    public void findKthBit() {
+        Solution solution = new Solution();
+        int n = 3;
+        int k = 1;
+        char result = solution.findKthBit(n, k);
+        assertEquals('0', result);
+        n = 4;
+        k=11;
+        result = solution.findKthBit(n, k);
+        assertEquals('1', result);
+        n=2;
+        k=3;
+        result = solution.findKthBit(n, k);
+        assertEquals('1', result);
+    }
+}