4 line 6ms Java Solution for P1


  • 0
    F

    we use bitwise XOR to solve this problem :

    0 ^ N = N
    N ^ N = 0
    So..... if N is the added number

    N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N

    = (N1^N1) ^ (N2^N2) ^..............^ (Nx^Nx) ^ N

    = 0 ^ 0 ^ ..........^ 0 ^ N

    = N

    public char findTheDifference(String s, String t) {
    		int  result = 0;
    		for (char c : s.toCharArray() ) {result = result ^ c;}
    		for (char c : t.toCharArray() ) {result = result ^ c;}
    		return (char)(result);
    	}
    

Log in to reply
 

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