Two Java Accepted Solutions.


  • 0
    E
    /*Of course we could just return Integer.bitCount(number); which in my opinion is best.
    The below method could be faster with more clever usage of Bitwise Operations,
     but seriously, an int is 32 bits at most... Worst case all 32 bits are set. 
    */Write the simple, readable solution and move on... 
    
    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            String binary = Integer.toBinaryString(n);
            int count = 0;
            for(int i = 0; i < binary.length(); i++){
             int bit = (n >> i) & 1;
              if(bit == 1)
                count++;
            }
            return count;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.