Four lines of code for JAVA


  • 13
    T

    public class Solution {
    public int singleNumber(int[] A) {
    int result = 0;
    for (int i : A)
    result ^= i ;
    return result ;
    }
    }


  • 0
    A

    IF elements are not is pair then we cannot apply this method. In that case we have to iterate through the array?


  • 5
    Y

    Just to make it more readable:

    public class Solution { 
        public int singleNumber(int[] A) {
            int result = 0; 
            for (int i : A) result ^= i ; 
            return result ; 
        } 
    }

  • 0
    S

    I wonder if there were an element appears for four times, this will fail, however it seems that leetcode doesn't check this case.


  • 0
    B

    Would it? Wouldn't it still eliminate the duplicate bits and leave you with the unique bits?


  • 0
    S

    I mean {2, 2, 4, 4, 4, 4} 4 repeats 4 times, 2 repeats 2 times, we should return 4, cause this one didn't appear twice....well the statement of the problem just needs to be clear。


  • 0
    A

    "single number"...The name of this question may indicate that mean...


Log in to reply
 

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