The Wayback Machine - https://web.archive.org/web/20240918021146/https://www.geeksforgeeks.org/program-decimal-binary-conversion/
Open In App

Program for Decimal to Binary Conversion

Last Updated : 22 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Basic
55.75%
21.9K

Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number.

Examples of Decimal to Binary: 

 
Input : 7
Output : 111
Input : 10
Output : 1010
Input: 33
Output: 100001


Brute force Approach

For Example: 
If the decimal number is 10. 
Step 1: Remainder when 10 is divided by 2 is zero. Therefore, arr[0] = 0. 
Step 2: Divide 10 by 2. New number is 10/2 = 5. 
Step 3: Remainder when 5 is divided by 2 is 1. Therefore, arr[1] = 1. 
Step 4: Divide 5 by 2. New number is 5/2 = 2. 
Step 5: Remainder when 2 is divided by 2 is zero. Therefore, arr[2] = 0. 
Step 6: Divide 2 by 2. New number is 2/2 = 1. 
Step 7: Remainder when 1 is divided by 2 is 1. Therefore, arr[3] = 1. 
Step 8: Divide 1 by 2. New number is 1/2 = 0. 
Step 9: Since number becomes = 0. Print the array in reverse order. Therefore the equivalent binary number is 1010.

The below diagram shows an example of converting the decimal number 17 to an equivalent binary number. 

Decimal to Binary


Below is the implementation of the above idea.  

C++
// C++ program to convert a decimal
// number to binary number

#include <iostream>
using namespace std;

// function to convert decimal to binary
void decToBinary(int n)
{
    // array to store binary number
    int binaryNum[32];

    // counter for binary array
    int i = 0;
    while (n > 0) {

        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }

    // printing binary array in reverse order
    for (int j = i - 1; j >= 0; j--)
        cout << binaryNum[j];
}

// Driver program to test above function
int main()
{
    int n = 17;
    decToBinary(n);
    return 0;
}
C
// C Code to convert Decimal number into Binary

#include <stdio.h>

void decToBinary(int n)
{
    // array to store binary number
    int binaryNum[32];
 
    // counter for binary array
    int i = 0;
    while (n > 0) {
        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }
 
    // printing binary array in reverse order
    for (int j = i - 1; j >= 0; j--)
        printf("%d", binaryNum[j]);
}
 
// Driver program to test above function
int main()
{
    int n = 17;
    decToBinary(n);
    return 0;
}
Java
// Java program to convert a decimal
// number to binary number
import java.io.*;

class GFG {
    // function to convert decimal to binary
    static void decToBinary(int n)
    {
        // array to store binary number
        int[] binaryNum = new int[32];

        // counter for binary array
        int i = 0;
        while (n > 0) {
            // storing remainder in binary array
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }

        // printing binary array in reverse order
        for (int j = i - 1; j >= 0; j--)
            System.out.print(binaryNum[j]);
    }

    // driver program
    public static void main(String[] args)
    {
        int n = 17;
        decToBinary(n);
    }
}

// Contributed by Pramod Kumar
C#
// C# program to convert a decimal
// number to binary number
using System;

public class GFG {

    // function to convert decimal
    // to binary
    static void decToBinary(int n)
    {
        // array to store binary number
        int[] binaryNum = new int[32];

        // counter for binary array
        int i = 0;
        while (n > 0) {
            // storing remainder in
            // binary array
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }

        // printing binary array
        // in reverse order
        for (int j = i - 1; j >= 0; j--)
            Console.Write(binaryNum[j]);
    }

    // Driver Code
    public static void Main()
    {
        int n = 17;
        decToBinary(n);
    }
}

// This code is contributed by Sam007.
JavaScript
<script>

// Javascript program to convert a decimal
// number to binary number

// function to convert decimal to binary
function decToBinary(n)
{
    // array to store binary number
    let binaryNum = new Array(32);

    // counter for binary array
    let i = 0;
    while (n > 0) {

        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = Math.floor(n / 2);
        i++;
    }

    // printing binary array in reverse order
    for (let j = i - 1; j >= 0; j--)
        document.write(binaryNum[j]);
}

// Driver program to test above function
    let n = 17;
    decToBinary(n);
    
// This code is contributed by Mayank Tyagi

</script>
PHP
<?php
// PHP program to convert a decimal
// number to binary number

// function to convert
// decimal to binary
function decToBinary($n)
{
    // array to store
    // binary number
    $binaryNum;

    // counter for binary array
    $i = 0;
    while ($n > 0) 
    {

        // storing remainder
        // in binary array
        $binaryNum[$i] = $n % 2;
        $n = (int)($n / 2);
        $i++;
    }

    // printing binary array
    // in reverse order
    for ($j = $i - 1; $j >= 0; $j--)
        echo $binaryNum[$j];
}

// Driver Code
$n = 17;
decToBinary($n);

// This code is contributed by m_kit
?>
Python3
# Python3 program to convert a 
# decimal number to binary number

# function to convert
# decimal to binary
def decToBinary(n):
    
    # array to store
    # binary number
    binaryNum = [0] * n

    # counter for binary array
    i = 0;
    while (n > 0): 

        # storing remainder
        # in binary array
        binaryNum[i] = n % 2
        n = int(n / 2)
        i += 1

    # printing binary array
    # in reverse order
    for j in range(i - 1, -1, -1):
        print(binaryNum[j], end = "")

# Driver Code
n = 17
decToBinary(n)

# This code is contributed by mits

Output
10001





Time complexity: O(logn) & Auxiliary Space: O(1) 

We can use bitwise operators to do the above job. Note that bitwise operators work faster than arithmetic operators used above.

C++
// CPP program to Decimal to binary conversion
// using bitwise operator
// Size of an integer is assumed to be 32 bits
#include <iostream>
using namespace std;

// Function that convert Decimal to binary
void decToBinary(int n)
{
    // Size of an integer is assumed to be 32 bits
    for (int i = 31; i >= 0; i--) {
        int k = n >> i;
        if (k & 1)
            cout << "1";
        else
            cout << "0";
    }
}

// driver code
int main()
{
    int n = 32;
    decToBinary(n);
}
C
// C language to convert Decimal to binary number
// using bitwise operator
// Size of an integer is assumed to be 32 bits

#include <stdio.h>

// Function that convert Decimal to binary
int decToBinary(int n)
{
    // Size of an integer is assumed to be 32 bits
    for (int i = 31; i >= 0; i--) {
        int k = n >> i; // right shift
        if (k & 1) // helps us know the state of first bit
              printf("1");
        else printf("0");
    }
}

// driver code
int main()
{
    int n = 32;
    decToBinary(n);
}
Java
// Java program to Decimal to binary conversion
// using bitwise operator
// Size of an integer is assumed to be 32 bits

class gfg {
    // Function that convert Decimal to binary
    public void decToBinary(int n)
    {
        // Size of an integer is assumed to be 32 bits
        for (int i = 31; i >= 0; i--) {
            int k = n >> i;
            if ((k & 1) > 0)
                System.out.print("1");
            else
                System.out.print("0");
        }
    }
}

class geek {
    // driver code
    public static void main(String[] args)
    {
        gfg g = new gfg();
        int n = 32;
        g.decToBinary(n);
    }
}
// This code is contributed by mits
C#
// C# program to Decimal to binary conversion
// using bitwise operator
// Size of an integer is assumed to be 32 bits
using System;
class gfg {
    // Function that convert Decimal to binary
    public void decToBinary(int n)
    {
        // Size of an integer is assumed to be 32 bits
        for (int i = 31; i >= 0; i--) {
            int k = n >> i;
            if ((k & 1) > 0)
                Console.Write("1");
            else
                Console.Write("0");
        }
    }
}

class geek {
    // driver code
    public static int Main()
    {
        gfg g = new gfg();
        int n = 32;
        g.decToBinary(n);
        return 0;
    }
}
JavaScript
<script>

// javascript program to Decimal to binary conversion
// using bitwise operator
// Size of an integer is assumed to be 32 bits


    // Function that convert Decimal to binary
    function decToBinary(n)
    {
        // Size of an integer is assumed to be 32 bits
        for (i = 31; i >= 0; i--) {
            var k = n >> i;
            if ((k & 1) > 0)
                document.write("1");
            else
                document.write("0");
        }
    }

    // driver code
    var n = 32;
    decToBinary(n);

// This code contributed by Princi Singh 

</script>
PHP
<?php
// PHP program to Decimal to binary conversion
// using bitwise operator

// Size of an integer is assumed 
// to be 32 bits

// Function that convert Decimal to binary
function decToBinary($n)
{
    
    // Size of an integer is
    // assumed to be 32 bits
    for ( $i = 31; $i >= 0; $i--) 
    {
        $k = $n >> $i;
        if ($k & 1)
            echo "1";
        else
            echo "0";
    }
}

    // Driver Code
    $n = 32;
    decToBinary($n);

// This code is contributed by aj_36
?>
Python3
# Python3 program to Decimal
# to binary conversion using
# bitwise operator

# Size of an integer is
# assumed to be 32 bits

# Function that convert
# Decimal to binary


def decToBinary(n):

    # Size of an integer is
    # assumed to be 32 bits
    for i in range(31, -1, -1):
        k = n >> i
        if (k & 1):
            print("1", end="")
        else:
            print("0", end="")


# Driver Code
n = 32
decToBinary(n)

# This code is contributed by mits

Output
00000000000000000000000000100000





Time complexity: O(1) 

loop iterates constant(32) number of times everytime even for small number 

Auxiliary Space: O(1)

Efficient Approach

It’s another efficient approach to converting Decimal to binary using the right shift(>>) and And(&) operator. Here we’ll use only Binary Operators which usually are very fast in computation.

C++
#include <bits/stdc++.h>
using namespace std;

string DecimalToBinary(int num)
{
    string str;
      while(num){
      if(num & 1) // 1
        str+='1';
      else // 0
        str+='0';
      num>>=1; // Right Shift by 1  
    }    
      return str;
}

void reverse(string str)
{
  for(int i=str.size()-1 ; i>=0 ; i--)
   cout<< str[i]; 
}

int main() {
    int num = 59;
    cout<< "Binary of num 59 is: ";
      reverse( DecimalToBinary(num) );
    return 0;
}
Java
// Java program to implement the
// above approach
import java.io.*;

class GFG 
{

  // the converts decimal to binary base
  static String DecimalToBinary(int num)
  {
    String str = "";
    while (num > 0) {
      if ((num & 1) == 1) // 1
        str += '1';
      else // 0
        str += '0';
      num >>= 1; // Right Shift by 1
    }
    return str;
  }

  // reverse the string
  static void reverse(String str)
  {
    for (int i = str.length() - 1; i >= 0; i--)
      System.out.print(str.charAt(i));
  }
  public static void main(String[] args)
  {
    int num = 59;
    System.out.print("Binary of num 59 is: ");
    reverse(DecimalToBinary(num));
  }
}

// This code is contributed by phasing17
C#
// C# program to implement the
// above approach

using System;

public class GFG
{
  
    // this converts decimal to binary base
    public static string DecimalToBinary(int num)
    {
        string str = "";
        while (num > 0) {
            if ((num & 1) == 1) // 1
                str += '1';
            else // 0
                str += '0';
            num >>= 1; // Right Shift by 1
        }
        return str;
    }
    // reverse the string
    public static void reverse(String str)
    {
        for (int i = str.Length - 1; i >= 0; i--)
            Console.Write(str[i]);
    }
    // Driver Code
    public static void Main(string[] args)
    {
        int num = 59;
        Console.Write("Binary of num 59 is: ");
        reverse(DecimalToBinary(num));
    }
}

// this code was contributed by phasing17
JavaScript
<script>
// JavaScript program to implement the approach
// function to convert decimal to binary
function DecimalToBinary(num)
{
    var str = "";
    while (num) 
    {
    
        // adding the result of num & 1 to str
        if (num & 1) // 1
            str += '1';
        else // 0
            str += '0';
            
        // Right Shift by 1
        num >>= 1;
    }
    return str;
}

// function to print reverse of str
function reverse(str)
{
    var res = "";
    for (var i = str.length - 1; i >= 0; i--)
        res += (str[i]);
    document.write(res);
}

// Driver Code
var num = 59;
document.write("Binary of num " + num + " is: ");

// function call
reverse(DecimalToBinary(num));

// This code is contributed by phasing17
</script>
Python3
# Python3 program to implement the above approach
# function to convert the decimal number
# to binary number
def DecimalToBinary(num):
    strs = ""
    while num:
        # if (num & 1) = 1
        if (num & 1):
            strs += "1"
        # if (num & 1) = 0
        else:
            strs += "0"
        # right shift by 1
        num >>= 1
    return strs

# function to reverse the string
def reverse(strs):
    print(strs[::-1])

# Driver Code
num = 59
print("Binary of num 59 is:", end=" ")
reverse(DecimalToBinary(num))

# This code is contributed by phasing17

Output
Binary of num 59 is: 111011





Time Complexity:  O(log n) & Auxiliary Space: O(1) 

Decimal to binary conversion can also be done without using arrays. 

C++
// C++ implementation of the approach
#include <cmath>
#include <iostream>
using namespace std;

#define ull unsigned long long int

// Function to return the binary
// equivalent of decimal value N
int decimalToBinary(int N)
{
    // To store the binary number
    ull B_Number = 0;
    int cnt = 0;
    while (N != 0) {
        int rem = N % 2;
        ull c = pow(10, cnt);
        B_Number += rem * c;
        N /= 2;
        // Count used to store exponent value
        cnt++;
    }
    return B_Number;
}

// Driver code
int main()
{
    int N = 17;
    cout << decimalToBinary(N);
    return 0;
}

// This code is contributed by Sania Kumari Gupta (kriSania804)
C
// C implementation of the approach
#include <math.h>
#include <stdio.h>

#define ull unsigned long long int

// Function to return the binary
// equivalent of decimal value N
int decimalToBinary(int N)
{
    // To store the binary number
    ull B_Number = 0;
    int cnt = 0;
    while (N != 0) {
        int rem = N % 2;
        ull c = pow(10, cnt);
        B_Number += rem * c;
        N /= 2;
        // Count used to store exponent value
        cnt++;
    }
    return B_Number;
}

// Driver code
int main()
{
    int N = 17;
    printf("%u", decimalToBinary(N));
    return 0;
}

// This code is contributed by Sania Kumari Gupta (kriSania804)
Java
// Java implementation of the approach 
import java.io.*;

class GFG 
{

// Function to return the binary 
// equivalent of decimal value N 
static int decimalToBinary(int N) 
{ 

    // To store the binary number 
    int B_Number = 0; 
    int cnt = 0; 
    while (N != 0)
    { 
        int rem = N % 2; 
        double c = Math.pow(10, cnt); 
        B_Number += rem * c; 
        N /= 2; 

        // Count used to store exponent value 
        cnt++; 
    } 

    return B_Number; 
} 

// Driver code 
public static void main (String[] args)
{
    
    int N = 17; 
    System.out.println (decimalToBinary(N)); 

}
}

// This code is contributed by ajit. 
C#
// C# implementation of the approach
using System;

class GFG
{
    
// Function to return the binary 
// equivalent of decimal value N 
static int decimalToBinary(int N) 
{ 

    // To store the binary number 
    int B_Number = 0; 
    int cnt = 0; 
    while (N != 0)
    { 
        int rem = N % 2; 
        int c = (int)Math.Pow(10, cnt); 
        B_Number += rem * c; 
        N /= 2; 

        // Count used to store exponent value 
        cnt++; 
    } 

    return B_Number; 
} 

// Driver code 
static public void Main ()
{
    int N = 17; 
    Console.Write(decimalToBinary(N)); 
}
}

// This code is contributed by Tushil. 
JavaScript
<script>

// javascript implementation of the approach 

// Function to return the binary 
// equivalent of decimal value N 
function decimalToBinary(N) 
{ 

    // To store the binary number 
    var B_Number = 0; 
    var cnt = 0; 
    while (N != 0)
    { 
        var rem = N % 2; 
        var c = Math.pow(10, cnt); 
        B_Number += rem * c; 
        N = parseInt(N/2); 

        // Count used to store exponent value 
        cnt++; 
    } 
    return B_Number; 
} 

// Driver code 
var N = 17; 
document.write(decimalToBinary(N)); 

// This code is contributed by Princi Singh 
</script>
Python3
# Python3 implementation of the approach 

# Function to return the binary 
# equivalent of decimal value N 
def decimalToBinary(N):
    
    # To store the binary number 
    B_Number = 0
    cnt = 0
    while (N != 0):
        rem = N % 2
        c = pow(10, cnt) 
        B_Number += rem * c 
        N //= 2
        
        # Count used to store exponent value 
        cnt += 1
    
    return B_Number 

# Driver code 
N = 17
print(decimalToBinary(N))

# This code is contributed by 
# SHUBHAMSINGH10

Output
10001





Time complexity: O(logn) & Auxiliary Space: O(1) 

Note that this method is similar to the one where we convert Binary to Decimal as discussed in this post.
There is yet another method that converts any Decimal Number to its Binary form. The idea is to use bitset.

Below is the implementation of the above approach. 

C++
//C++ program to convert a decimal number
//to its binary form.

//including header file
#include <bits/stdc++.h>
using namespace std;

//Function to convert a decimal number
//to its binary form
string decimalToBinary(int n)
{
    //finding the binary form of the number and 
    //converting it to string. 
    string s = bitset<64> (n).to_string();
    
    //Finding the first occurrence of "1"
    //to strip off the leading zeroes.
    const auto loc1 = s.find('1');
    
    if(loc1 != string::npos)
        return s.substr(loc1);
    
    return "0";
}

//Driver Code
int main()
{
    int n = 17;
    
    //Function call
    cout << decimalToBinary(n);

    return 0;
}

//This code is contributed by yashbeersingh42
Java
// Java program to convert a decimal number to its binary
// form
import java.util.*;

class DecimalToBinary {

  // Function to convert a decimal number to its binary
  // form
  public static String decimalToBinary(int n)
  {

    // Finding the binary form of the number and
    // converting it to a string
    String s = Integer.toBinaryString(n);

    // Finding the first occurrence of "1" to strip off
    // the leading zeroes
    int loc1 = s.indexOf("1");

    if (loc1 != -1) {
      return s.substring(loc1);
    }
    return "0";
  }

  // Driver code
  public static void main(String[] args)
  {
    int n = 17;

    // Function call
    System.out.println(decimalToBinary(n));
  }
}

// This code is contributed by phasing17
C#
// C# program to convert a decimal number
// to its binary form.
using System;

class HelloWorld {

  // Function to convert a decimal number
  // to its binary form
  public static String decimalToBinary(int n)
  {
    // finding the binary form of the number and 
    //converting it to string. 
    String s = Convert.ToString(n, 2);

    return s;
  }

  static void Main() {

    int n = 17;

    //Function call
    Console.WriteLine(decimalToBinary(n));

  }
}

// The code is contributed by Nidhi goel. 
JavaScript
// Javascript program to convert a decimal number
// to its binary form.

// Function to convert a decimal number
// to its binary form
function decimalToBinary( n)
{
    // finding the binary form of the number and 
    // converting it to string. 
    const s = n.toString(2);
    
    return s;
}

// Driver Code
let n = 17;

// Function call
console.log(decimalToBinary(n));

  // This code is contributed by imruhrbf8.
Python3
# Python program to convert a decimal number
# to its binary form.

# Function to convert a decimal number
# to its binary form
def decimalToBinary( n):
  
    # finding the binary form of the number and 
    # converting it to string. 
    s = bin(n)[2:]

    # Finding the first occurrence of "1"
    # to strip off the leading zeroes.
    # const auto loc1 = s.find('1')
    loc1 = s[s.index('1'):]

    
    return loc1
    
    return "0"

# Driver Code
n = 17

# Function call
print(decimalToBinary(n))

Output
10001





Time complexity: O(logn) & Auxiliary Space: O(1) 

Another Approach

C++
// C++ program to convert Decimal to Binary Number
#include <bits/stdc++.h>
using namespace std;

int main()
{

    // input number
    int number = 15;
    int n = (int)(log2(number));
  
    // binary output
    // using the inbuilt function
    cout << "the binary number is : "
         << bitset<64>(number).to_string().substr(64 - n
                                                  - 1);
}

// This code is written by phasing17
Java
//To convert Decimal to Binary Number//
import java.util.*;
    public class Main{
        public static void main(String [] args){
            //input//
            int number =15;
            
            //output//
            System.out.println("the binary number is : "+ Integer.toString(number,2));
            
            //This code is written by ZEESHAN AHMAD//
        }
    }
C#
// To convert Decimal to Binary Number//
using System;
    class GFG{
        public static void Main(){
            //  input//
            int number =15;
             
            //output//
            Console.WriteLine("the binary number is : "+ Convert.ToString(number, 2));
        }
    }

// This code is contributed by code_hunt.
JavaScript
// JavaScript program to convert Decimal to Binary Number

// input number
var number = 15;

// binary output
// using the inbuilt function
console.log("the binary number is :", number.toString(2));

// This code is written by phasing17

    
Python3
# Python3 program to convert Decimal to Binary Number

# input number
number = 15

# binary output
# using the inbuilt function
print("the binary number is :", bin(number)[2::])

# This code is written by phasing17

Output
the binary number is : 1111





Time complexity: O(logn) & Auxiliary Space: O(1) 
 



Previous Article
Next Article

Similar Reads

Program for Binary To Decimal Conversion
Given a binary number as input, we need to write a program to convert the given binary number into an equivalent decimal number. Check: Binary to Decimal ConverterExamples :  Input : 111Output : 7Input : 1010Output : 10Input: 100001Output: 33Recommended PracticeBinary number to decimal numberTry It!The idea is to extract the digits of a given binar
15+ min read
Decimal to binary conversion without using arithmetic operators
Find the binary equivalent of the given non-negative number n without using arithmetic operators. Examples: Input : n = 10Output : 1010 Input : n = 38Output : 100110 Note that + in below algorithm/program is used for concatenation purpose. Algorithm: decToBin(n) if n == 0 return "0" Declare bin = "" Declare ch while n &gt; 0 if (n &amp; 1) == 0 ch
8 min read
Program for Octal to Decimal Conversion
Given an octal number as input, we need to write a program to convert the given octal number into equivalent decimal number. Examples: Input : 67Output: 55Input : 512Output: 330Input : 123Output: 83The idea is to extract the digits of a given octal number starting from the rightmost digit and keep a variable dec_value. At the time of extracting dig
11 min read
Program for decimal to hexadecimal conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16. Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 and 10-15 are represented by characters from A - F.
8 min read
Program for Decimal to Octal Conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent octal number. i.e convert the number with base value 10 to base value 8. The base value of a number system determines the number of digits used to represent a numeric value. For example, the binary number system uses two digits 0 and 1
10 min read
Decimal to octal conversion with minimum use of arithmetic operators
Given a decimal number n without floating-point. The problem is to convert the decimal number to octal number with minimum use of arithmetic operators. Examples: Input : n = 10 Output : 12 12 is octal equivalent of decimal 10. Input : n = 151 Output : 227 Approach: Following are the steps: Perform decimal to binary conversion without using arithmet
8 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Gray to Binary and Binary to Gray conversion
Binary Number is the default way to store numbers, but in many applications, binary numbers are difficult to use and a variety of binary numbers is needed. This is where Gray codes are very useful. Gray code has a property that two successive numbers differ in only one bit because of this property gray code does the cycling through various states w
13 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
Sum of decimal equivalents of binary node values in each level of a Binary Tree
Given a Binary Tree consisting of nodes with values 0 and 1 only, the task is to find the total sum of the decimal equivalents of the binary numbers formed by connecting nodes at the same level from left to right, on each level. Examples: Input: Below is the given Tree: 0 / \ 1 0 / \ / \ 0 1 1 1Output: 9Explanation: Binary number formed at level 1
15 min read
8086 program to convert a 16 bit decimal number to binary
Problem: We are given a 16 bit decimal number we have to print the number in binary format Examples: Input: d1 = 16 Output: 10000 Input: d1 = 7 Output: 111 Explanation: Load the value stored into registerDivide the value by 2 to convert it to binaryPush the remainder into the stackIncrease the countRepeat the steps until the value of the register i
2 min read
Program to convert a Binary Number to Hexa-Decimal Number
Given a Binary Number, the task is to convert this Binary number to its equivalent Hexa-Decimal Number.Examples: Input: 100000101111 Output: 82F Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1111. Here, 1000 is equivalent to 8, 0010 is equivalent to 2 and 1111 is equivalent to F Therefore, the number becomes 82FInput:10101
10 min read
Javascript Program To Find Decimal Equivalent Of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent. Input: 0-&gt;0-&gt;0-&gt;1-&gt;1-&gt;0-&gt;0-&gt;1-&gt;0Output: 50 Input: 1-&gt;0-&gt;0Output: 4The decimal value of an empty linked list is considered as 0. Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node's data to
3 min read
Conversion of Binary number to Base 4 system
We all know that, [Tex]2^2 [/Tex]= [Tex]4^1 [/Tex]. In other words, single digit in base 4 can be represented using 2 digits in base 2. Base 2 has digits 0 and 1. Similarly base 4 has digits 0, 1, 2 and 3. Algorithm for Binary to Base 4 Conversion Beginning from right, group the digits of binary (base 2) number into group of two. Write the base 4 e
1 min read
Number of substrings with odd decimal value in a binary string
Given a binary string containing only 0's and 1's. Write a program to find number of sub-strings of this string whose decimal representation is odd. Examples : Input : 101 Output : 3 Explanation : Substrings with odd decimal representation are: {1, 1, 101} Input : 1101 Output : 6 Explanation : Substrings with odd decimal representation are: {1, 1,
6 min read
Decimal representation of given binary string is divisible by 20 or not
The problem is to check whether the decimal representation of the given binary number is divisible by 20 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or the minimum numbers of multiplication and division operations. No leadings 0’s are there in the input. Ex
14 min read
Sum of decimal equivalent of all possible pairs of Binary representation of a Number
Given a number N. The task is to find the sum of the decimal equivalent of all the pairs formed from the binary representation of the given number. Examples: Input: N = 4 Output: 4 Binary equivalent of 4 is 100. All possible pairs are 10, 10, 00 and their decimal equivalent are 2, 2, 0 respectively. So, 2 + 2+ 0 = 4 Input: N = 11 Output: 13 All pos
5 min read
Decimal to Binary using recursion and without using power operator
Given an integer N, the task is convert and print the binary equaiva;ent of N.Examples: Input: N = 13 Output: 1101Input: N = 15 Output: 1111 Approach Write a recursive function that takes an argument N and recursively calls itself with the value N / 2 as the new argument and prints N % 2 after the call. The base condition will be when N = 0, simply
3 min read
Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
Given a binary-valued Undirected Graph with V vertices and E edges, the task is to find the maximum decimal equivalent among all the connected components of the graph. A binary-valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: 3 Explanation: Decimal equivalents of the c
14 min read
Check if decimal representation of Binary String is divisible by 9 or not
Given a binary string S of length N, the task is to check if the decimal representation of the binary string is divisible by 9 or not. Examples: Input: S = 1010001Output:YesExplanation: The decimal representation of the binary string S is 81, which is divisible by 9. Therefore, the required output is Yes. Input: S = 1010011Output: NoExplanation: Th
12 min read
Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted
Given an array arr[] consisting of N positive integers, the task is to rearrange the array such that the reversed binary representation of all the array elements is sorted. If the decimal equivalent of reversed binary representations of two or more array elements is equal, then the original value is taken into consideration while rearranging the ar
13 min read
Check if level-wise Decimal equivalent of Binary Tree forms a Monotonic sequence or not
Given the root of a binary tree in which all nodes has values either 0 or 1, the task is to check if the level-wise decimal equivalent of given Tree forms a monotonic sequence.or not. A sequence is monotonic if it is either monotone increasing or monotone decreasing. A sequence nums is monotone increasing if for all i &lt;= j, nums[i] &lt;= nums[j]
15+ min read
Convert Binary to Decimal in Swift
In computers, we use two main number systems: binary (with 0s and 1s) and decimal (with numbers from 0 to 9). Converting binary numbers (like 1010) into decimal numbers (like 10) is a common task in programming. In this article, we'll learn how to do this in Swift, a programming language developed by Apple. Problem StatementThe problem is to conver
2 min read
Counting even decimal value substrings in a binary string
Given a binary string of size N. Count all substring that have even decimal value considering binary to decimal conversion from left to right (For example a substring "1011" is treated as 13) Examples : Input : 101Output : 2Explanation : Substring are : 1, 10, 101, 0, 01, 1 In decimal form : 1, 1, 3, 0, 2, 1 There are only 2 even decimal value subs
9 min read
BCD or Binary Coded Decimal
Binary Coded Decimal, or BCD, is another process for converting decimal numbers into their binary equivalents. It is a form of binary encoding where each digit in a decimal number is represented in the form of bits.This encoding can be done in either 4-bit or 8-bit (usually 4-bit is preferred).It is a fast and efficient system that converts the dec
3 min read
Decimal Equivalent of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent. Input : 0-&gt;0-&gt;0-&gt;1-&gt;1-&gt;0-&gt;0-&gt;1-&gt;0 Output : 50 Input : 1-&gt;0-&gt;0 Output : 4The decimal value of an empty linked list is considered as 0. Recommended PracticeDecimal Equivalent of Binary Linked ListTry It!Initialize the result as 0. Traverse the linked li
10 min read
Maximum decimal value path in a binary matrix
Given binary square matrix [n*n]. Find maximum integer value in a path from top left to bottom right. We compute integer value using bits of traversed path. We start at index [0,0] and end at index [n-1][n-1]. from index [i, j], we can move [i, j+1] or [i+1, j]. Examples: Input : mat[][] = {{1, 1, 0, 1}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 1, 1}} Ou
14 min read
Convert Binary fraction to Decimal
Given an string of binary number n. Convert binary fractional n into it's decimal equivalent. Examples: Input: n = 110.101 Output: 6.625 Input: n = 101.1101 Output: 5.8125We strongly recommend that you click here and practice it, before moving on to the solution. Following are the steps of converting binary fractional to decimal. A) Convert the int
6 min read
Queries for decimal values of subarrays of a binary array
Given a binary array arr[], we to find the number represented by the subarray a[l..r]. There are multiple such queries. Examples: Input : arr[] = {1, 0, 1, 0, 1, 1}; l = 2, r = 4 l = 4, r = 5 Output : 5 3 Subarray 2 to 4 is 101 which is 5 in decimal. Subarray 4 to 5 is 11 which is 3 in decimal. Input : arr[] = {1, 1, 1} l = 0, r = 2 l = 1, r = 2 Ou
11 min read
Binary to decimal and vice-versa in python
Write Python code for converting a decimal number to it's binary equivalent and vice-versa. Example: From decimal to binary Input : 8 Output : 1 0 0 0 From binary to decimal Input : 100 Output : 4 Decimal to binary Keep calling conversion function with n/2 till n &gt; 1, later perform n % 1 to get MSB of converted binary number. Example :- 7 1). 7/
4 min read