My 3 lines c++ solution 9ms


  • 3
    Y
    class Solution {
    public:
        int hammingWeight(uint32_t n) {
    		int count=0;
    		for(int i=0;i<32;i++)	if(n>>i & 1) count++;
    		return count;
        }
    };

  • 0
    H

    I ran the code with 19ms. Why?


  • 0
    C

    Improve on exit condition for smaller n values and removing conditional :

     int res= 0;
     for(; n; n >>=1) res += n & 1;
     return res;
    

Log in to reply
 

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