ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขทศนิยม แปลงเป็นรูปแบบทวินิยม (binary) จากนั้นกลับบิต 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
คำอธิบายเพิ่มเติม
การทำงานนี้เรียกว่า Bitwise NOT หรือการกลับบิต (bit inversion) ใน JavaScript สามารถทำได้ง่ายด้วยตัวดำเนินการ ~ (tilde) แต่ต้องระวังเรื่อง signed 32-bit integer โค้ดตัวอย่างใช้วิธี string manipulation ซึ่งเข้าใจง่ายแต่อาจช้ากว่าการใช้ bitwise operator โดยตรง