Java XOR - 4 lines


  • 0
    J

    This problem is similar to https://leetcode.com/problems/single-number/description/

    In both cases, we use XOR or cancel elements out with each other.

    'a' XOR 'a' == 97 XOR 97 == 0

    public class Solution {
        public char findTheDifference(String s, String t) {
            int xor = 0;
            for(int i = 0; i < s.length(); i++) xor ^= s.charAt(i);
            for(int i = 0; i < t.length(); i++) xor ^= t.charAt(i);
            return (char)xor;
        }
    }
    

Log in to reply
 

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