6ms XOR JAVA solution


  • 1
    R

    based on the XOR equations:
    Given:
    a ^ a = 0
    b ^ 0 = b
    and XOR, order does not match

    Then:
    a ^ b ^ a = (a ^ a) ^ b = 0 ^ b = b, is b is the number. all other pairs XOR equals 0

    public char findTheDifference(String s, String t) {
        
        int num = 0;
        for (char c : s.toCharArray()) {
            num ^= (c - 'a');
        }
        
        for (char c : t.toCharArray()) {
            num ^= (c - 'a');
        }
        
        return (char)('a' + num);
    }

Log in to reply
 

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