Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หาความต่างระหว่างสองสตริงใน 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