55
56
kamyu104/src/main.rsCopy file name to clipboard Expand all lines: kamyu104/src/main.rs +1 Lines changed: 1 addition & 0 deletions 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;
Original file line number Diff line number Diff line change
1
+ // Time: O(logn) = O(32)
2
+ // Space: O(1)
3
+
4
+ pub struct Solution { }
5
+
6
+ impl Solution {
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;
14
+ }
15
+ }
16
+
17
+ #[ cfg( test) ]
18
+ mod tests {
19
+ use super :: * ;
20
+
21
+ #[ test]
22
+ fn test_hamming_weight ( ) {
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
+ ) ;
41
+ }
42
+ }
Original file line number Diff line number Diff line change @@ -54,7 +54,7 @@ mod tests {
54
54
use super :: * ;
55
55
56
56
#[ test]
57
- fn test_add ( ) {
57
+ fn test_single_number ( ) {
58
58
assert_eq ! ( Solution1 :: single_number( vec![ 2 , 2 , 3 , 2 ] ) , 3 ) ;
59
59
assert_eq ! ( Solution1 :: single_number( vec![ 0 , 1 , 0 , 1 , 0 , 1 , 99 ] ) , 99 ) ;
60
60
assert_eq ! ( Solution1 :: single_number( vec![ 0 , 0 , 0 , 1 , 1 , 1 , 5 ] ) , 5 ) ;
You can’t perform that action at this time.
0 commit comments