Skip to content

Instantly share code, notes, and snippets.

@tewari2312
Created May 5, 2024 15:33
Show Gist options
  • Select an option

  • Save tewari2312/7c343b736e3b695885acee6c6884f4ca to your computer and use it in GitHub Desktop.

Select an option

Save tewari2312/7c343b736e3b695885acee6c6884f4ca to your computer and use it in GitHub Desktop.
class HammingWeightCalculator {
public static void main(String[] args) {
System.out.println(new HammingWeightCalculator().hammingWeight(11));
System.out.println(new HammingWeightCalculator().hammingWeight(128));
System.out.println(new HammingWeightCalculator().hammingWeight(2147483645));
}
public int hammingWeight(int n) {
String value = Integer.toBinaryString(n);
int returnValue = 0;
for (Character c: value.toCharArray()){
if(c=='1')
returnValue++;
}
return returnValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment