Accepted Java solution, but I have a question to ask

  • 0

    The following below is the accepted Java solution, however, if I change " >>>" to ">>", it will result in "time limit exceed ". So can anybody tell me why?

    public class Solution {

    public int hammingWeight(int n) {
       int count = 0;
       while(n != 0){
           if((n & 1) == 1){
           n = n >>> 1;
       return count;


  • 7

    is arithmetic shift right, >>> is logical shift right.
    In an arithmetic shift, the sign bit is extended to preserved the signedness of the number.
    For example, -2 in 8 bits would be 11111110 (because the most significant bit has negative weight).
    Shifting it right one bit using arithmetic shift would give you 11111111, or -1.
    Logical right shift, however, does not care that the value could possibly represent a number;
    it simply moves everything to the right and fills in from the left with 0s.
    Shifting our -2 right one bit using logical shift would give 01111111.
    The time limit exceeded case is the following one:
    in which case the n will never be 0 when you use >> because the most significant bit 1 is preserved for ever.

Log in to reply

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