Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:389. 找不同,ASCII码求和,JavaScript,详细注释 #277

Open
chencl1986 opened this issue Jan 25, 2021 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/find-the-difference/

解题思路:

  1. 每个字符的ASCII码都是一个固定的数字。
  2. s和t中的字符,除了一个之外,其余都相同,也就是ASCII码都相同。
  3. 只要将t中所有字符的ASCII码求和,减去s中字符的ASCII码之和,剩下的就是被添加到t中字符的ASCII码。
  4. 使用String.fromCharCode将ASCII码转换成字符串即可。
  5. charCodeAtString.fromCharCode替换成codePointAtString.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);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant