Skip to content

Commit 14e01c7

Browse files
committed
Count bits
1 parent 027ec64 commit 14e01c7

4 files changed

Lines changed: 60 additions & 0 deletions

File tree

count_bits/Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "count_bits"
3+
version = "0.1.0"
4+
edition = "2024"
5+
6+
[dependencies]

count_bits/src/lib.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
pub fn count_bits(n: usize) -> Vec<usize> {
2+
let mut result = Vec::with_capacity(n + 1);
3+
result.push(0);
4+
let mut power = 1;
5+
for i in 1..=n {
6+
if i == power * 2 {
7+
power = i;
8+
}
9+
result.insert(i, 1 + result[i - power]);
10+
}
11+
println!("{:?}", result);
12+
return result;
13+
}
14+
15+
#[cfg(test)]
16+
mod tests {
17+
use super::*;
18+
19+
#[test]
20+
fn test_count_bits_1() {
21+
let result = count_bits(2);
22+
assert_eq!(result, vec![0, 1, 1]);
23+
}
24+
25+
#[test]
26+
fn test_count_bits_2() {
27+
let result = count_bits(5);
28+
assert_eq!(result, vec![0, 1, 1, 2, 1, 2]);
29+
}
30+
}

src/SUMMARY.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,7 @@
5656
* [Product except self](./product_except_self/introduction.md)
5757
* [Max sub array sum](./max_sub_array_sum/introduction.md)
5858
* [Max vowels in substring](./maximum-number-of-vowels/introduction.md)
59+
* [Count bits](./count_bits/introduction.md)
60+
61+
62+

src/count_bits/introduction.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Count 1s For Each Entry
2+
Return an array where each element at index i (0 ≤ i ≤ n) is the number of 1's in the binary representation of i.
3+
4+
5+
```rust,ignore
6+
pub fn count_bits(n: usize) -> Vec<usize> {
7+
let mut result = Vec::with_capacity(n + 1);
8+
result.push(0);
9+
let mut power = 1;
10+
for i in 1..=n {
11+
if i == power * 2 {
12+
power = i;
13+
}
14+
result.insert(i, 1 + result[i - power]);
15+
}
16+
return result;
17+
}
18+
19+
```
20+
[Source](https://github.com/ratulb/programming_problems_in_rust/blob/master/count_bits/src/lib.rs)

0 commit comments

Comments
 (0)