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;
12mod reverse_bits;
23mod single_number;
34mod single_number_ii;
4- mod number_of_1_bits;
55mod template;
Original file line number Diff line number Diff line change 1+ // Time: O(logn) = O(32)
2+ // Space: O(1)
3+
14pub struct Solution { }
25
36impl 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}
You can’t perform that action at this time.
0 commit comments