Created
May 5, 2024 15:33
-
-
Save tewari2312/7c343b736e3b695885acee6c6884f4ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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