summaryrefslogtreecommitdiff
path: root/counting-bits/src/main.rs
blob: 120359442ffa8744251a96fb0dd0aff0cb886dfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
}