给我们两个字符串,例如s和t。字符串t由随机改组字符串s生成,然后在随机位置再添加一个字母。
我们需要编写一个JavaScript函数,该函数接受这两个字符串并返回添加到t的字母。
例如-
如果输入字符串为-
const s = "abcd", t = "abcde";
那么输出应该是-
const output = "e";
因为“ e”是添加的字母。
const s = "abcd", t = "abcde";
const findTheDifference = (s, t) => {
let a = 0, b = 0; let charCode, i = 0;
while(s[i]){
a ^= s.charCodeAt(i).toString(2);
b ^= t.charCodeAt(i).toString(2);
i++;
};
b^=t.charCodeAt(i).toString(2);
charCode = parseInt(a^b,2);
return String.fromCharCode(charCode);
};
console.log(findTheDifference(s, t));输出结果
控制台中的输出将是-
e