diff options
author | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
---|---|---|
committer | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
commit | 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb (patch) | |
tree | 0072cca328fe5adb2ed61004010228ff85e2164d /counting-bits/src |
Diffstat (limited to 'counting-bits/src')
-rw-r--r-- | counting-bits/src/main.rs | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/counting-bits/src/main.rs b/counting-bits/src/main.rs new file mode 100644 index 0000000..1203594 --- /dev/null +++ b/counting-bits/src/main.rs @@ -0,0 +1,23 @@ +fn main() { + let tests = [ + (2, vec![0,1,1]), + (5, vec![0,1,1,2,1,2]) + ]; + + for test in tests { + println!("{} is {:?} should be {:?}", test.0, count_bits(test.0), test.1); + } +} + +fn count_bits(n: i32) -> Vec<i32> { + let mut solution: Vec<i32> = Vec::new(); + for i in 0..=n { + let mut ones = 0; + for c in 0..32 { + ones += (1<<c & i != 0) as i32; + } + solution.push(ones); + } + + return solution; +} |