ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ตัวเลขทศนิยม แปลงเป็นเลขฐานสองและย้อนกลับ 1 บิตเป็น 0 และ 0 เป็น 1 และคืนค่าทศนิยมที่เทียบเท่ากับไบนารีใหม่ที่เกิดขึ้น
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const num = 45657;
const reverseBitsAndConvert = (num = 1) => {
const binary = num.toString(2);
let newBinary = '';
for(let i = 0; i < binary.length; i++){
const bit = binary[i];
newBinary += bit === '1' ? '0' : 1;
};
const decimal = parseInt(newBinary, 2);
return decimal;
};
console.log(reverseBitsAndConvert(num)); ผลลัพธ์
19878