Skip to main content

Binary Number to Decimal Number

Problem​

Given a Binary Number B, find its decimal equivalent.

Examples:​

Example 1:

Input: B = 10001000
Output: 136

Example 2:

Input: B = 101100
Output: 44

Your task:​

You don't need to read or print anything. Your task is to complete the function binary_to_decimal() which takes the binary number as string input parameter and returns its decimal equivalent.

  • Expected Time Complexity: O(K∗Log(K))O(K * Log(K)), where K is number of bits in binary number.
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1<=1 <= number of bits in binary number <=16<= 16

Solution​

Python​

def binary_to_decimal(self, str):
num = int(str);
dec_value = 0;
base = 1;
temp = num;
while(temp):
last_digit = temp % 10;
temp = int(temp / 10);
dec_value += last_digit * base;
base = base * 2;
return dec_value;

Java​

public int binary_to_decimal(String str) {
int decValue = 0;
int base = 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) == '1') {
decValue += base;
}
base = base * 2;
}
return decValue;
}

C++​

int binary_to_decimal(string str) {
unsigned long long num = bitset<64>(str).to_ullong();
int decValue = static_cast<int>(num);
return decValue;
}

C​

int binary_to_decimal(char str[]) {
int len = strlen(str);
int dec_value = 0;
int base = 1;
int i;
for (i = len - 1; i >= 0; i--) {
if (str[i] == '1') {
dec_value += base;
}
base *= 2;
}
return dec_value;
}
  • Time Complexity: O(K∗Log(K))O(K * Log(K))
  • Auxiliary Space: O(1)O(1)