Skip to content

Commit c31d23d

Browse files
author
SC
committed
feeat: completes Hamming weight exercise
1 parent 9cf7d74 commit c31d23d

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed
Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,27 @@
11
namespace _18_BitManipulation.L191_NumberOfOneBits;
22

33
public class Solution {
4-
public int HammingWeight(uint n)
4+
public int HammingWeightByMod(uint n)
55
{
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;
726
}
827
}

csharp/18_BitManipulation_Tests/L191_NumberOfOneBits_Tests.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,17 @@ public class L191_NumberOfOneBits_Tests
1010
[Test]
1111
public void Example1_Test()
1212
{
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+
1520
var solution = new Solution();
16-
var result = solution.HammingWeight(input);
21+
var result = solution.HammingWeightByMod(input);
1722

1823
result.Should().Be(4);
24+
1925
}
2026
}

0 commit comments

Comments
 (0)