A Simple Java solution


  • 2
    T
    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int sum=0;
            String[] x=Integer.toBinaryString(n).split("");
            for(int i =0 ;i< x.length;i++){
                if(x[i].equals("1")) sum++;
            }
            return sum;
        }
    }

  • 2
    O

    use Integer.bitCount(n) may be easier.


Log in to reply
 

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