Javascript solution using sum of characters


  • 8
    E
    var findTheDifference = function(s, t) {
        if (s.length === 0) return t;
        var letters = 'abcdefghijklmnopqrstuvwxyz';
        var sSum = s.split('').map(e => e.charCodeAt(0) - 'a'.charCodeAt(0)).reduce((a, b) => a + b);
        var tSum = t.split('').map(e => e.charCodeAt(0) - 'a'.charCodeAt(0)).reduce((a, b) => a + b);
        return letters[tSum -sSum];
    };
    

  • 2
    T

    You can use xor operation but you need to convert character to it's unicode value and back to character.

    function findTheDifference(s, t) {
        //convert char to num, since xor operator will cast char to num
        let c = t.charCodeAt(t.length-1);           
        for(let i=0; i < s.length; i++){
            c = c ^ s.charCodeAt(i) ^ t.charCodeAt(i);
        }
        return String.fromCharCode(c);
    };
    
    

  • 0
    K
    var findTheDifference = function(s, t) {
        var l = s.length;
        var c = t.charCodeAt(s.length);
        for (var i=0; i<l; i+=1){
            c -= s.charCodeAt(i);
            c += t.charCodeAt(i);
        }
        return String.fromCharCode(c);
    };
    

Log in to reply
 

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