Java solution, no bit shifting


  • 0
    S

    n & -n gives the first digit which is non-zero. e.g. 3 -> 1, 10->2, 9->1, 24->8

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int res = 0;
            int last = (n & -n);
            while (last != 0)   {
                res += 1;
                n -= last;
                last = (n & -n);
            }
            return res;
        }
    }

Log in to reply
 

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