File tree Expand file tree Collapse file tree 2 files changed +29
-5
lines changed Expand file tree Collapse file tree 2 files changed +29
-5
lines changed Original file line number Diff line number Diff line change
1
+ mod number_of_1_bits;
1
2
mod reverse_bits;
2
3
mod single_number;
3
4
mod single_number_ii;
4
- mod number_of_1_bits;
5
5
mod template;
Original file line number Diff line number Diff line change
1
+ // Time: O(logn) = O(32)
2
+ // Space: O(1)
3
+
1
4
pub struct Solution { }
2
5
3
6
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;
6
14
}
7
15
}
8
16
@@ -12,7 +20,23 @@ mod tests {
12
20
13
21
#[ test]
14
22
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
+ ) ;
17
41
}
18
42
}
You can’t perform that action at this time.
0 commit comments