Convert Binary to Decimal

Problem Statement: Convert a binary number to a decimal number.

Examples:

Example 1:
Input: N = 1011
Output: 11
Explanation: 1011 when converted to decimal number is “11”.

Example 2:
Input: 100
Output: 4
Explanation: 100 when converted to decimal number is “4”.

Solution:

DisclaimerDon’t jump directly to the solution, try it out yourself first.

Solution 1:

Intuition: The idea is to add the appropriate power of 2 to the final answer, whenever the bit is set.

Approach:

  • Take the input as a string.
  • Traverse from rightmost character to left.
  • Maintain a integer base and multiply it by 2 everytime,to store values of pow(2,i).
  • Now check if char is ‘1’ or ‘0’,if it is ‘1’ add base to your final answer.

Code:

C++ Code

#include<bits/stdc++.h>
using namespace std;
int main() {
	string s = "1011";
	int n = s.length();
	int base = 1;
	int ans = 0;
	for (int i = n - 1; i >= 0; i--) {
		if (s[i] == '1') {
			ans += base;
		}
		base *= 2;
	}
	cout << ans;
}

Output: 11

Time Complexity: O(N), as we are iterating over just one for a loop.

Space Complexity: O(1).

Java Code

public class Main {
  public static void main(String args[]) {
    String s = "1011";
    int n = s.length();
    int base = 1;
    int ans = 0;
    for (int i = n - 1; i >= 0; i--) {
      if (s.charAt(i) == '1') {
        ans += base;
      }
      base *= 2;
    }
    System.out.print(ans);
  }
}

Output: 11

Time Complexity: O(N), as we are iterating over just one for a loop.

Space Complexity: O(1).

Solution 2: Using predefined functions.

For C++:

Syntax: stoi(string s, int position, int base)

Approach: Position will be 0 since it is the starting position and base will be 2 since the input is in binary.

For Java:

Syntax: Integer.parseInt(String s,int base)

Approach: Base will be 2 since the input is in binary

Code:

.

C++ Code

#include<bits/stdc++.h>
using namespace std;
int main() {
	string s = "1011";
	cout << stoi(s, 0, 2);
}

Output: 11

Time Complexity: O(N).

Space Complexity: O(1).

Java Code

public class Main {
  public static void main(String args[]) {
    String s = "1011";
    System.out.print(Integer.parseInt(s, 2));
  }
}

Output: 11

Time Complexity: O(N).

Space Complexity: O(1).

Special thanks to Pranav Padawe for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article