Something wrong with my C++ solution


  • 0
    R

    Can someone tell me what is wrong with this C++ solution?

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            if (n == 1 || n == 0) return n&1;
            return (n&1 + hammingWeight(n>>1));
        }
    };
    

    I am basically going through each bit, seeing if it is a 1 or 0, and then truncating the number to the next bit (at least, that is what I think I am doing), recursively.

    For ex when called on:
    0010100
    n&1 = 0
    001010
    n&1 = 0
    00101
    n&1 = 1
    0010
    n&1 = 0
    001
    n&1 = 1

    we add these and get 2, which is the correct response. Is this what my code doing?


  • 1
    T

    note that '+' is prior to '&'.


  • 0
    R

    @tianoak thank you - I didn't know that!


Log in to reply
 

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