十进制到二进制转换

十进制数字也可以转换为二进制格式。要将十进制数转换为二进制数,我们需要将数字除以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

以上是 十进制到二进制转换 的全部内容, 来源链接: utcz.com/z/350229.html

回到顶部