File tree Expand file tree Collapse file tree 2 files changed +30
-5
lines changed
18_BitManipulation/L191-NumberOfOneBits Expand file tree Collapse file tree 2 files changed +30
-5
lines changed Original file line number Diff line number Diff line change 1
1
namespace _18_BitManipulation . L191_NumberOfOneBits ;
2
2
3
3
public class Solution {
4
- public int HammingWeight ( uint n )
4
+ public int HammingWeightByMod ( uint n )
5
5
{
6
- throw new NotImplementedException ( ) ;
6
+ var numberOfOnes = 0 ;
7
+
8
+ for ( int i = 0 ; i < 32 ; i ++ )
9
+ {
10
+ // select the order of magnitued in base 2
11
+ // by bit-shifting 1
12
+ var shiftedI = 1 << i ;
13
+
14
+ // bitwise logical AND
15
+ // 0 * 0 = 0
16
+ // 0 * 1 = 0
17
+ // 1 * 1 = 1
18
+ var bitWiseMultip = shiftedI & n ;
19
+
20
+ // increase number of 1 bits
21
+ if ( bitWiseMultip != 0 )
22
+ numberOfOnes ++ ;
23
+ }
24
+
25
+ return numberOfOnes ;
7
26
}
8
27
}
Original file line number Diff line number Diff line change @@ -10,11 +10,17 @@ public class L191_NumberOfOneBits_Tests
10
10
[ Test ]
11
11
public void Example1_Test ( )
12
12
{
13
- uint input = 10111 ;
14
-
13
+ uint input = 0b10111 ;
14
+ var x = input << 1 ;
15
+ byte a = 3 ;
16
+ byte b = 0b_0011 ;
17
+ bool c = a == b ;
18
+
19
+
15
20
var solution = new Solution ( ) ;
16
- var result = solution . HammingWeight ( input ) ;
21
+ var result = solution . HammingWeightByMod ( input ) ;
17
22
18
23
result . Should ( ) . Be ( 4 ) ;
24
+
19
25
}
20
26
}
You can’t perform that action at this time.
0 commit comments