字串間的差值 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

更新於: 23-11-2020

2K+ 檢視

開啟您的 事業

完成課程並獲得認證

開始
廣告
© . All rights reserved.