Skip to content

Commit 3a2e60d

Browse files
authored
Create Find Kth Bit in Nth Binary String.java
1 parent 0190cfd commit 3a2e60d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public char findKthBit(int n, int k) {
3+
return nthString(n).charAt(k - 1);
4+
}
5+
6+
private String nthString(int n) {
7+
if (n == 1) {
8+
return "0";
9+
}
10+
String prevString = nthString(n - 1);
11+
return prevString + "1" + reverseAndInvert(prevString);
12+
}
13+
14+
private String reverseAndInvert(String s) {
15+
char[] chars = s.toCharArray();
16+
for (int i = 0; i < s.length(); i++) {
17+
chars[i] = chars[i] == '1' ? '0' : '1';
18+
}
19+
StringBuilder sb = new StringBuilder(String.valueOf(chars));
20+
return sb.reverse().toString();
21+
}
22+
}

0 commit comments

Comments
 (0)