My Java solution using bit shift


  • 0
    X

    I am not sure when should I use >> or >>>. It seems they do the same work here in this problem. Any why isn't there a <<< in Java?
    And comment?

    I found this which might help: http://www.quora.com/Why-there-is-no-unsigned-left-shift-operator-in-Java

    below is my solution:

    public int singleNumber(int[] nums) {
    	int[] count = new int[32];
    	int result = 0;
    	for (int i = 0; i < nums.length; i++) {
    		int cNum = nums[i];
    		for (int j = 0; j < 32; j++) {
    			count[j] = count[j] + (cNum & 1);
    			cNum = cNum >>> 1;
    		}
    		// System.out.println(Arrays.toString(count));
    	}
    
    	for (int i = 0; i < 32; i++) {
    		result = result << 1;
    		result = result + count[32 - i - 1] % 3;
    	}
    	return result;
    }

  • 0
    Y

    The difference between >> and >>> is when you deal with negative numbers.
    For example:
    5>>3 0000 0000 0000 ..... 0101 -> 0000 0000 0000 .... 0001 add zeros from right
    -5>>3 1111 1111 1111 .... 1011 -> 1111 1111 1111 .... 1111 add ones from right
    -5>>>3 1111 1111 1111 .... 1011 -> 0001 1111 1111 ..... 1111 add zeros from right
    And the reason why there is no <<< is that when you move left, whether it is a negative number, you just add zero from right.


Log in to reply
 

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