JAVA TLE question


  • 0
    Y

    when i used >> operator,it runs out TLE.However, when i used >>>,it works fine.Is there anyone who can help me?Thanks!

    This is TLE code:

    public int hammingWeight(int n) {
    
        int one=0;
        while(n!=0){
            one+=n&1;
            n=n>>1;
        }
    
    return one;
    

    }
    '''


  • 0
    X

    The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
    so when the first bit is 1, if use >>, 1 will always be there, then the loop will never end.


  • 0
    J

    One more question. The while loop works when using while(n!=0). But it doesn't work when using while(n>0). Why?

    Thx


  • 0
    Y

    @xinerd Great!Thanks!


  • 0
    X

    @Jessica we also have to handle negative number which the first bit is 1.
    if n>0, it also handle number which the first bit is 0.


Log in to reply
 

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