Skip to content

Commit 243965e

Browse files
committed
leetcode week2-2
1 parent 0b8f2d0 commit 243965e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

counting-bits/bus710.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// T: O(n log n)
2+
// S: O(n)
3+
4+
pub fn count_bits(n: i32) -> Vec<i32> {
5+
// Prepare a vector.
6+
// The first item can just be 0
7+
let mut vec = Vec::from([0]);
8+
9+
// Iterate as many as the given number + 1
10+
for num in 1..n + 1 {
11+
// Get a binary string from the number (ex: 2 => 10)
12+
let num_str = format!("{num:b}");
13+
// Count '1' from the given binary string
14+
let cnt = num_str.chars().filter(|c| *c == '1').count();
15+
// Store the number in the vector
16+
vec.push(cnt as i32);
17+
}
18+
19+
vec
20+
}
21+
22+
#[cfg(test)]
23+
mod tests {
24+
use super::*;
25+
26+
#[test]
27+
fn it_works() {
28+
let result = count_bits(2);
29+
assert_eq!(result, Vec::from([0, 1, 1]));
30+
31+
let result2 = count_bits(5);
32+
assert_eq!(result2, Vec::from([0, 1, 1, 2, 1, 2]));
33+
}
34+
}

0 commit comments

Comments
 (0)