十进制到二进制转换
十进制数字也可以转换为二进制格式。要将十进制数转换为二进制数,我们需要将数字除以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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志