Accepted Java solution using left shift


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

Log in to reply
 

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