Number of 1 Bits LeetCode
Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
Example 1:
Input: n = 11
Output: 3
Explanation:
The input binary string 1011 has a total of three set bits.
Example 2:
Input: n = 128
Output: 1
Explanation:
The input binary string 10000000 has a total of one set bit.
Example 3:
Input: n = 2147483645
Output: 30
Explanation:
The input binary string 1111111111111111111111111111101 has a total of thirty set bits.
Constraints:
1 <= n <= 231 - 1
Follow up: If this function is called many times, how would you optimize it?
Approach 1: Using Built in functiion
class Solution {
public int hammingWeight(int n) {
int count = Integer.bitCount(n);
return count;
}
}
Approach 2 :
📘 Explanation:
Term | Meaning |
---|---|
1 << i | Shifts 1 to the left by i bits to create a mask like 00001000 |
n & mask | Checks if the i-th bit in n is 1 |
!= 0 | If the result is not zero, it means that bit was a 1 |
class Solution {
public int hammingWeight(int n) {
int count = 0; // To keep track of number of 1s
// Loop through all 32 bits of the integer
for (int i = 0; i < 32; i++) {
// Create a mask by left-shifting 1 by i positions
// This helps check each bit from 0th to 31st
int mask = 1 << i;
// Use bitwise AND to check if the ith bit of n is 1
if ((n & mask) != 0) {
count++; // If the result is not 0, that bit is set (1)
}
}
// Return the total number of set bits
return count;
}
}
public class codefile{
static int solve(String s){
int n = Integer.parseUnsignedInt(s, 2);
//return Integer.bitCount(n); // using built in function
int count=0;
for(int i=0;i<32;i++)
{
int mask=1<<i;
if((mask & n) !=0)
{
count++;
}
}
return count;
}
}
Comments
Post a Comment