O(1) Solution 32 times bit operations


  • 0
    X

    This is a loop with 32 iterations, each includes one bit shifting and one bit-wise and. I think the complexity is O(1). Correct me please if I made any mistake.

       class Solution {
        public:
            int hammingWeight(uint32_t n) {
                int i = 0, sum = 0;
                uint32_t one = 1;
                for(i = 0; i < 32; i++){
                    sum += ((n>>i) & one);
                }
                return sum;
            }
        };

  • 0
    L

    What about "n = n & (n - 1)" to set the rightmost bit to one instead of iterating 32 times?


  • 0
    L
    This post is deleted!

Log in to reply
 

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