Why my code TLE


  • 0
    A
    public int hammingWeight(int n) {
        int counter = 0;
        while(n!=0) {
            if ((n & 1) == 1)
                counter++;
            n = n >> 1;
        }
        return counter;
    }
    

    It seems that the time complexity is O(n) but n is 32 bits integer and best 0 times, worst 32 times. Using for loop always 32 times. Isn't while loop better?


  • 0
    Z

    Try to use unsigned right shift '>>>' operator: n= n>>>1;, this will shift the sigh bit. So if MSB is 1, n won't be 0 in your code.


  • 0
    L

    why 5 line can't use code "if(n%2!=0)count++;",please tell me.


Log in to reply
 

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