原题链接:leetcode-cn.com/problems/fi…
解题思路:
- 每个字符的ASCII码都是一个固定的数字。
- s和t中的字符,除了一个之外,其余都相同,也就是ASCII码都相同。
- 只要将t中所有字符的ASCII码求和,减去s中字符的ASCII码之和,剩下的就是被添加到t中字符的ASCII码。
- 使用
String.fromCharCode
将ASCII码转换成字符串即可。 - 将
charCodeAt
和String.fromCharCode
替换成codePointAt
和String.fromCodePoint
也是同样效果。
/**
* @param {string} s
* @param {string} t
* @return {character}
*/
var findTheDifference = function (s, t) {
let code = 0; // 保存ASCII码的值
// 遍历将t中所有字符ASCII码的值求和
for (const char of t) {
code += char.charCodeAt(0);
}
// 因为t比s多一个字符,因此只要将t中字符ASCII码减去s的ASCII码,剩下的一个就是被添加的字符
for (const char of s) {
code -= char.charCodeAt(0);
}
// 将ASCII码转换成字符串,就得到了结果
return String.fromCharCode(code);
};