เราต้องเขียนฟังก์ชันบวกสองอาร์เรย์ที่มีเฉพาะ '0' และ '1' แทนเลขฐานสอง คืนอาร์เรย์ผลบวก
กฎการบวกฐานสอง: 0+0=0, 0+1=1, 1+0=1, 1+1=10 (มี carry)
ตัวอย่าง: ['1','0','1'] + ['1','0','1'] = ['1','0','1','0']
ตัวอย่างโค้ด
const arr1 = ['1', '0', '1'];
const arr2 = ['1', '0', '1'];
const addBinary = (arr1 = [], arr2 = []) => {
const str1 = arr1.join('');
const str2 = arr2.join('');
let carry = 0, temp = 0, res = '';
for (let i = Math.max(str1.length, str2.length) - 1; i >= 0; i--) {
const el1 = +str1[i] || 0;
const el2 = +str2[i] || 0;
if (el1 + el2 + carry > 1) { temp = 0; carry = 1; }
else { temp = el1 + el2 + carry; carry = 0; }
res = temp + res;
}
if (carry) { res = carry + res; }
return res.split('');
};
console.log(addBinary(arr1, arr2));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
[ '1', '0', '1', '0' ]