Two Java Solutions using XOR / Sum


  • 5
    M

    Solution 1: XOR

    public char findTheDifference(String a, String b) {
        char result = 0;
        for (char x : a.toCharArray()) result ^= x;
        for (char x : b.toCharArray()) result ^= x;
        return result;
    }
    

    Solution 2: Sum (+/-)

    public char findTheDifference(String a, String b) {
        char result = b.charAt(b.length() - 1);
        for (int i = 0; i < a.length(); i++) {
            result += b.charAt(i);
            result -= a.charAt(i);
        }
        return result;
    }
    

  • 0
    B

    For the "Sum" solution, is it possible to get an overflow?


  • 1
    M

    @braydenCN Thanks. I'm also concerning about overflow when doing sum. But it seems that even in the case of underflow or overflow, the final result is still correct. Anyway, XOR is easier and more reliable.

    // Test with:
    String a = "\uFFFE\uFFFF";
    String b = "\uFFFF\uFFFE\u1234";
    
    // Return '\u1234'
    

Log in to reply
 

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