Skip to content

Commit 23e315e

Browse files
authored
Merge pull request #956 from bus710/week08
[bus710] Week 08
2 parents eb015aa + 9bdbaf8 commit 23e315e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

number-of-1-bits/bus710.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#[cfg(test)]
2+
mod tests {
3+
use super::*;
4+
5+
#[test]
6+
fn it_works() {
7+
let result = Solution::hamming_weight(11);
8+
assert_eq!(result, 3);
9+
let result = Solution::hamming_weight(128);
10+
assert_eq!(result, 1);
11+
let result = Solution::hamming_weight(2147483645);
12+
assert_eq!(result, 30);
13+
}
14+
}
15+
16+
#[derive(Debug)]
17+
struct Solution;
18+
19+
#[allow(dead_code)]
20+
impl Solution {
21+
pub fn hamming_weight(n: i32) -> i32 {
22+
let mut cnt: i32 = 0;
23+
let mut target_bit_holder: i32;
24+
25+
for i in 0..32 {
26+
target_bit_holder = n & (0x1 << i);
27+
if target_bit_holder != 0 {
28+
cnt += 1;
29+
}
30+
}
31+
32+
cnt
33+
}
34+
}

0 commit comments

Comments
 (0)