字符串间的差值 JavaScript
我们有两个字符串,分别为 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP