Skip to content

Commit 508e812

Browse files
committed
1545. Find Kth Bit in Nth Binary String: AC
1 parent 8e67db8 commit 508e812

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed

src/solution/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1165,3 +1165,4 @@ mod s1540_can_convert_string_in_k_moves;
11651165
mod s1541_minimum_insertions_to_balance_a_parentheses_string;
11661166
mod s1542_find_longest_awesome_substring;
11671167
mod s1544_make_the_string_great;
1168+
mod s1545_find_kth_bit_in_nth_binary_string;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
/**
2+
* [1545] Find Kth Bit in Nth Binary String
3+
*
4+
* Given two positive integers n and k, the binary string Sn is formed as follows:
5+
*
6+
* S1 = "0"
7+
* Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1
8+
*
9+
* Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).
10+
* For example, the first four strings in the above sequence are:
11+
*
12+
* S1 = "0"
13+
* S2 = "011"
14+
* S3 = "0111001"
15+
* S4 = "011100110110001"
16+
*
17+
* Return the k^th bit in Sn. It is guaranteed that k is valid for the given n.
18+
*
19+
* Example 1:
20+
*
21+
* Input: n = 3, k = 1
22+
* Output: "0"
23+
* Explanation: S3 is "<u>0</u>111001".
24+
* The 1^st bit is "0".
25+
*
26+
* Example 2:
27+
*
28+
* Input: n = 4, k = 11
29+
* Output: "1"
30+
* Explanation: S4 is "0111001101<u>1</u>0001".
31+
* The 11^th bit is "1".
32+
*
33+
*
34+
* Constraints:
35+
*
36+
* 1 <= n <= 20
37+
* 1 <= k <= 2^n - 1
38+
*
39+
*/
40+
pub struct Solution {}
41+
42+
// problem: https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/
43+
// discuss: https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/?currentPage=1&orderBy=most_votes&query=
44+
45+
// submission codes start here
46+
47+
impl Solution {
48+
pub fn find_kth_bit(n: i32, k: i32) -> char {
49+
let n = n as usize;
50+
let k = k as usize;
51+
let mut arr = vec![vec![]; n];
52+
53+
arr[0].push(false);
54+
for i in 1..n {
55+
let len = arr[i - 1].len();
56+
for j in 0..len {
57+
let v = arr[i - 1][j];
58+
arr[i].push(v);
59+
}
60+
arr[i].push(true);
61+
for j in (0..len).rev() {
62+
let v = !arr[i - 1][j];
63+
arr[i].push(v);
64+
}
65+
}
66+
67+
if arr[n - 1][k - 1] {
68+
'1'
69+
} else {
70+
'0'
71+
}
72+
}
73+
}
74+
75+
// submission codes end
76+
77+
#[cfg(test)]
78+
mod tests {
79+
use super::*;
80+
81+
#[test]
82+
fn test_1545_example_1() {
83+
let n = 3;
84+
let k = 1;
85+
86+
let result = '0';
87+
88+
assert_eq!(Solution::find_kth_bit(n, k), result);
89+
}
90+
91+
#[test]
92+
fn test_1545_example_2() {
93+
let n = 4;
94+
let k = 11;
95+
96+
let result = '1';
97+
98+
assert_eq!(Solution::find_kth_bit(n, k), result);
99+
}
100+
}

0 commit comments

Comments
 (0)