simple java solution bit by bit


  • 0
    I
    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int c = 0;
            for(int i = 0; i < 32; i++) {
                if((n & 1) == 1) c++;
                n >>= 1;
            }
            return c;
        }
    }
    

Log in to reply
 

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