เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ตัวเลขเป็นอาร์กิวเมนต์แรกและอาร์กิวเมนต์เดียว ฟังก์ชันควรใช้การเรียกซ้ำเพื่อสร้างสตริงที่แสดงถึงสัญกรณ์ไบนารีของตัวเลขนั้น
ตัวอย่างเช่น −
f(4) = '100' f(1000) = '1111101000' f(8) = '1000'
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const decimalToBinary = (num) => {
if(num >= 1) {
// If num is not divisible by 2 then recursively return proceeding
// binary of the num minus 1, 1 is added for the leftover 1 num
if (num % 2) {
return decimalToBinary((num - 1) / 2) + 1;
} else {
// Recursively return proceeding binary digits
return decimalToBinary(num / 2) + 0;
}
} else {
// Exit condition
return '';
};
};
console.log(decimalToBinary(4));
console.log(decimalToBinary(1000));
console.log(decimalToBinary(8)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์บนคอนโซล -
100 1111101000 1000