Skip to content

Commit af545e8

Browse files
committed
fix number_of_1_bits
1 parent 664dad1 commit af545e8

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

kamyu104/src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
mod number_of_1_bits;
12
mod reverse_bits;
23
mod single_number;
34
mod single_number_ii;
4-
mod number_of_1_bits;
55
mod template;

kamyu104/src/number_of_1_bits.rs

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
1+
// Time: O(logn) = O(32)
2+
// Space: O(1)
3+
14
pub struct Solution {}
25

36
impl Solution {
4-
pub fn hamming_weight(n: i32) -> i32 {
5-
n
7+
pub fn hamming_weight(mut n: u32) -> u8 {
8+
let mut cnt: u8 = 0;
9+
while n > 0 {
10+
cnt += 1;
11+
n &= n - 1;
12+
}
13+
return cnt;
614
}
715
}
816

@@ -12,7 +20,23 @@ mod tests {
1220

1321
#[test]
1422
fn test_hamming_weight() {
15-
assert_eq!(Solution::hamming_weight(3), 3);
16-
assert_eq!(Solution::hamming_weight(4), 4);
23+
assert_eq!(
24+
Solution::hamming_weight(
25+
u32::from_str_radix("00000000000000000000000000001011", 2).unwrap()
26+
),
27+
3
28+
);
29+
assert_eq!(
30+
Solution::hamming_weight(
31+
u32::from_str_radix("00000000000000000000000010000000", 2).unwrap()
32+
),
33+
1
34+
);
35+
assert_eq!(
36+
Solution::hamming_weight(
37+
u32::from_str_radix("11111111111111111111111111111101", 2).unwrap()
38+
),
39+
31
40+
);
1741
}
1842
}

0 commit comments

Comments
 (0)