Problem Name: 191. Number of 1 Bits
Problem Link: https://leetcode.com/problems/number-of-1-bits/description/
Difficulty: Easy
Tag: Divide and Conquer | Bit Manipulation
Language: C# | C++
OJ: LeetCode
Algorithm:
Convert the unsigned integer n to its binary representation as a string.
Iterate through each character in the binary string.
Convert each character to an integer (0 or 1) by subtracting the ASCII value of '0'.
Add the converted integer to the count.
Return the final count as the Hamming weight.
Iterate through each character in the binary string.
Convert each character to an integer (0 or 1) by subtracting the ASCII value of '0'.
Add the converted integer to the count.
Return the final count as the Hamming weight.
Code(C#)
public class Solution {
public int HammingWeight(uint n) {
int count = 0;
string binaryString = Convert.ToString(n,2);
for(int i=0; i<binaryString.Length; i++)
count += ((int)(binaryString[i] - '0'));
return count;
}
}
Code(C++)
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt=0;
while(n>=1)
{
cnt+=(n%2);
n/=2;
}
return cnt;
}
};