Skip to content

Commit bae194d

Browse files
authored
Create find-kth-bit-in-nth-binary-string.cpp
1 parent 3ed793f commit bae194d

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
char findKthBit(int n, int k) {
7+
int flip = 0; // init bit (S1) is 0
8+
for (int l = (1 << n) - 1; k > 1; l /= 2) { // loop from Sn to S1, early return if k == 1
9+
if (k == l / 2 + 1) {
10+
flip ^= 1; // hit mid, xor 1
11+
break;
12+
}
13+
if (k > l / 2) {
14+
k = l + 1 - k;
15+
flip ^= 1; // right-hand side, invert once
16+
}
17+
}
18+
return '0' + flip;
19+
}
20+
};

0 commit comments

Comments
 (0)