C++程序 二进制转十进制转换
给定输入的二进制数,我们需要编写一个程序将给定的二进制数转换为等效的十进制数。
例子:
输入: 111
输出: 7
输入: 1010
输出: 10
输入: 100001
输出: 33
试一下!
这个想法是从给定的二进制数字从右侧开始提取数字并保持一个变量dec_value。在从二进制数提取数字时,将数字乘以适当的基数(2的幂),并将其加到变量dec_value中。最后,变量dec_value将存储所需的十进制数。
例如:
如果二进制数是111。
dec_value = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7
下图说明了如何将(1010)转换为等效的十进制值:

下面是上述思想的实现:
// C ++程序转换二进制到十进制#include <iostream>using namespace std; //将二进制转换为十进制的功能int binaryToDecimal(int n){ int num = n; int dec_value = 0; // 将基础值初始化为1,即2^0 int base = 1; int temp = num; while (temp) { int last_digit = temp % 10; temp = temp / 10; dec_value += last_digit * base; base = base * 2; } return dec_value;} // 驱动程序int main(){ int num = 10101001; cout << binaryToDecimal(num) << endl;} 输出:
169
时间复杂度: O(logn)
辅助空间: O(1)
注意: 该程序仅适用于整数范围内的二进制数。 如果要使用20位或30位等长的二进制数字,则可以使用字符串变量来存储二进制数字。
以下是一个类似的程序,它使用字符串变量代替整数来存储二进制值:
// C ++程序将二进制转换为十进制// 当输入表示为二进制字符串时。#include <iostream>#include <string>using namespace std; //将二进制转换为十进制的功能int binaryToDecimal(string n){ string num = n; int dec_value = 0; // 将基础值初始化为1,即2^0 int base = 1; int len = num.length(); for (int i = len - 1; i >= 0; i--) { if (num[i] == '1') dec_value += base; base = base * 2; } return dec_value;} // 驱动程序intmain(){ string num = "10101001"; cout << binaryToDecimal(num) << endl;} 输出:
169
时间复杂度: O(n),其中n是字符串的长度。
辅助空间: O(1)
使用预定义函数:
// C ++程序实现// 上述方法#include <iostream>using namespace std; // 驱动程序int main(){ char binaryNumber[] = "1001"; cout << stoi(binaryNumber, 0, 2); return 0;} 输出 :
9
时间复杂度: O(n),其中n是给定字符串的长度。
辅助空间: O(1)
