Why doesn't this solution work (C)?


  • 0
    R
     int hammingWeight(uint32_t n) {
      int count = 0;
      uint32_t bit = 1;
      
      while(n >= bit) {
          if(n & bit) {
              count++;
          }
          bit = bit << 1;
      }
      
      return count;
    }
    

    This solution time exceeded on n == 0. But it returns the correct answer immediately on my computer?


  • 0
    T

    Sorry, the driver code is a little buggy which reported wrong test case when TLE. It will be fixed soon.

    You solution should be correct when n == 0. The TLE was caused when n == 2147483648.


  • 0

    Thanks, this is just fixed.


  • 0
    R

    Cool, thank you!


  • 0
    R

    Hmm, why does it fail at n == 2147483648? It seems like it's doing the same thing as this working solution for me:

    int hammingWeight(uint32_t n) {
    int count = 0;

    while(n) {
    count += (n&1);
    n >>= 1;
    }

    return count;
    }

    My old solution just goes in the other direction.


  • 0
    T

    Because 2147483648 is not greater than 2147483648, and then shift to left 1 bit make bit == 0 instead of 2147483648 * 2. Then it fall into the infinity loop where bit always be 0.


Log in to reply
 

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