Binary to Decimal in C

Binary to Decimal in C
Binary to Decimal in C

Problem Statement: Given a Binary Number convert it to its equivalent decimal number. Binary to Decimal in C.

Examples:

Example 1:
Input: N = 101
Output: 5

Example 2:
Input: N = 1000
Output: 8

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

Approach:

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

  • Given a binary number.
  • Declare a variable to store the decimal number and initialize with 0 say dec = 0
  • Take the remainder of the binary number dividing by 10 and store it in variable rem.
  • Now dec = dec + rem * base, base starts with base = 1 and increases after each iteration base = base*2.
  • And reduce the binary number by dividing it by 10 after each iteration.
Binary to Decimal in C

Code:

C Program

#include<stdio.h>

int main()
{
    int N = 101;
    int num = N;
    int dec=0;
    int base = 1;
    while(N!=0)
    {
        int rem = N%10;
        dec = dec+rem*base;
        base = base*2;
        N = N/10;
    }
    printf("The decimal equivalent of %d is %d",num,dec);
}

Output: The decimal equivalent of 101 is 5

Time Complexity: O(n), where n is the length of the number

Space Complexity: O(1).

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