สามารถแปลงตัวเลขทศนิยมเป็นรูปแบบไบนารีได้ ในการแปลงเลขฐานสิบเป็นเลขฐานสอง เราต้องหารตัวเลขด้วย 2 จนกว่าจะถึง 0 หรือ 1 และในแต่ละขั้นตอน เศษที่เหลือจะถูกเก็บไว้ต่างหากเพื่อสร้างเลขฐานสองที่เท่ากันในลำดับที่กลับกัน
ในอัลกอริธึมนี้ เราจะทำตามวิธีการแบบเรียกซ้ำ จะช่วยให้เราแก้ปัญหาโดยไม่ต้องใช้โครงสร้างข้อมูลสแต็ก ในการใช้งาน เรารู้ว่าการเรียกซ้ำของฟังก์ชันจะเป็นไปตามสแต็กภายใน เราจะให้บริการงานของเราโดยใช้กองนั้น
อินพุตและเอาต์พุต
Input: Decimal number 56 Output: Binary Equivalent: 111000
อัลกอริทึม
decToBin(decimal)
ป้อนข้อมูล :เลขทศนิยม
ผลลัพธ์: สตริงเทียบเท่าไบนารี
Begin if decimal = 0 OR 1, then insert decimal into the binary string return decToBin(decimal / 2) insert (decimal mod 2) into the binary string. End
ตัวอย่าง
#include<iostream>
using namespace std;
void decToBin(int dec) {
if(dec == 1 || dec == 0) {
cout << dec; //print either 0 or 1 as dec
return;
}
decToBin(dec/2); //divide the number by 2 and find decimal again
cout << dec % 2; //after returning print the value in reverse order
}
main() {
int dec;
cout<<"Enter decimal number: "; cin >> dec;
cout << "Binary Equivalent: "; decToBin(dec);
} ผลลัพธ์
Enter decimal number: 56 Binary Equivalent: 111000