Java solution doubts


  • 0
    C
    public class Solution {
        public int hammingWeight(int n) {
          int count = 0;
          while (n != 0){
              count += ( (n % 2) == 1) ? 1 : 0;
            // count +=( (n & 1) == 1) ? 1 : 0;
              n = n >>> 1;
          }
          return count;
        }
    }
    

    In my solution, count += ( (n % 2) == 1) ? 1 : 0; will fail on test case with all bits = 1;
    However count +=( (n & 1) == 1) ? 1 : 0; will pass. So what is the reason for such situation. These two approaches do the same thing to me.


    Another question is about the difference between >> and >>> in Java. I know the latter one is for unsigned number. But what would these two operations actually do?


  • 3

    All bits 1 means the number is -1. And (-1)%2 in Java is -1, not 1.
    You can get it accepted with (n % 2) != 0).

    You can also do some debugging simply by printing. Try this after your count += line:

          System.out.println(n + " " + n % 2 + " " + count);
    

    >>> and >> both shift to the right. But >>> shifts in 0-bits while >> shifts in the high bit (so it keeps the sign of the number).


Log in to reply
 

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