Skip to content

Commit cb0d637

Browse files
authored
Create FindKthinNthBinaryString.java
1 parent 4c4f20c commit cb0d637

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

FindKthinNthBinaryString.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public char findKthBit(int n, int k) {
3+
return findKthBitHelper(n, k);
4+
}
5+
6+
private char findKthBitHelper(int n, int k) {
7+
8+
if (n == 1) {
9+
return '0';
10+
}
11+
12+
13+
int length = (1 << n) - 1;
14+
int mid = length / 2 + 1;
15+
16+
17+
if (k == mid) {
18+
return '1';
19+
}
20+
21+
22+
if (k < mid) {
23+
return findKthBitHelper(n - 1, k);
24+
} else {
25+
26+
int mirrorIndex = length - k + 1;
27+
char bit = findKthBitHelper(n - 1, mirrorIndex);
28+
return bit == '0' ? '1' : '0';
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)