diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README.md b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README.md index 27111b41d8e32..2c4dcff0aa261 100644 --- a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README.md +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README.md @@ -148,6 +148,22 @@ function queryString(s: string, n: number): boolean { } ``` +#### Rust + +```rust +func queryString(s string, n int) bool { + if n > 1000 { + return false + } + for i := n; i > n/2; i-- { + if !strings.Contains(s, strconv.FormatInt(int64(i), 2)) { + return false + } + } + return true +} +``` + diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md index a2376081d8344..9819fbff8ffc4 100644 --- a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md @@ -48,7 +48,13 @@ tags: -### Solution 1 +### Solution 1: Brain Teaser + +We observe that the length of string $s$ does not exceed $1000$, so string $s$ can represent at most $1000$ binary integers. Therefore, if $n \gt 1000$, then $s$ definitely cannot represent the binary representation of all integers in the range $[1,.. n]$. + +Additionally, for an integer $x$, if the binary representation of $x$ is a substring of $s$, then the binary representation of $\lfloor x / 2 \rfloor$ is also a substring of $s$. Therefore, we only need to check whether the binary representations of integers in the range $[\lfloor n / 2 \rfloor + 1,.. n]$ are substrings of $s$. + +The time complexity is $O(m^2 \times \log m)$ and the space complexity is $O(\log n)$, where $m$ is the length of string $s$ and $n$ is the positive integer given in the problem. @@ -133,6 +139,22 @@ function queryString(s: string, n: number): boolean { } ``` +#### Rust + +```rust +func queryString(s string, n int) bool { + if n > 1000 { + return false + } + for i := n; i > n/2; i-- { + if !strings.Contains(s, strconv.FormatInt(int64(i), 2)) { + return false + } + } + return true +} +``` + diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.rs b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.rs new file mode 100644 index 0000000000000..b84206f9bf998 --- /dev/null +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/Solution.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn query_string(s: String, n: i32) -> bool { + if n > 1000 { + return false; + } + for i in (n / 2 + 1..=n).rev() { + if !s.contains(&format!("{:b}", i)) { + return false; + } + } + true + } +}