Open In App

Convert a number from base 2 to base 6

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a binary integer N, the task is to convert it into base 6.

Note: The number of bits in N is up to 100. 

Examples:

Input: N = “100111”
Output: 103
Explanation: The given integer (100111)2 is equivalent to (103)6.

Input: N = “1111111”
Output: 331

 

Approach: The given problem can be solved by first converting the given integer to decimal, thereafter converting the number from decimal to the base 6 using an approach discussed here. Please note that since the value of the N can reach up to 2100, the 128-bit integer can be used to store the decimal number. 

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Program to convert the base of
// given binary number to base 6
void convertBase(string N)
{
    // 128 bit integer to store
    // the decimal conversion
    __int128 decimal = 0;
 
    // Loop to iterate N
    for (int i = 0; i < N.length(); i++) {
        // Binary to decimal
        decimal = decimal * 2 + (N[i] - '0');
    }
 
    // Stores the base 6 int
    vector<int> ans;
 
    // Decimal to base 6
    while (decimal > 0) {
        ans.push_back(decimal % 6);
        decimal = decimal / 6;
    }
 
    // Print Answer
    for (int i = ans.size() - 1; i >= 0; i--) {
        cout << ans[i];
    }
}
 
// Driver Code
int main()
{
    string N = "100111";
    convertBase(N);
 
    return 0;
}


C




// C program to implement the above approach
#include <stdio.h>
#include <stdint.h>
#include <string.h>
 
// Program to convert the base of
// given binary number to base 6
void convertBase(char* N)
{
    // 128 bit integer to store
    // the decimal conversion
    __int128 decimal = 0;
     
      //calculating length of N
      int len = strlen(N);
    // Loop to iterate N
    for (int i = 0; i < len; i++) {
        // Binary to decimal
        decimal = decimal * 2 + (N[i] - '0');
    }
 
    // Stores the base 6 int
    int ans[len];
       
      //to calculate index in ans
      int pos = 0;
 
    // Decimal to base 6
    while (decimal > 0) {
        ans[pos++] = (decimal % 6);
        decimal = decimal / 6;
    }
 
    // Print Answer
    for (int i = pos - 1; i >= 0; i--) {
        printf("%d", ans[i]);
    }
}
 
// Driver Code
int main()
{
    char* N = "100111";
    convertBase(N);
 
    return 0;
}
 
// This code is contributed by phalasi.


Java




// JAVA program of the above approach
import java.util.*;
class GFG {
 
    // Program to convert the base of
    // given binary number to base 6
    public static void convertBase(String N)
    {
 
        // 128 bit integer to store
        // the decimal conversion
        int decimal = 0;
 
        // Loop to iterate N
        for (int i = 0; i < N.length(); i++) {
            // Binary to decimal
            decimal = decimal * 2 + (N.charAt(i) - '0');
        }
 
        // Stores the base 6 int
        ArrayList<Integer> ans = new ArrayList<Integer>();
 
        // Decimal to base 6
        while (decimal > 0) {
            ans.add(decimal % 6);
            decimal = decimal / 6;
        }
 
        // Print Answer
        for (int i = ans.size() - 1; i >= 0; i--) {
            System.out.print(ans.get(i));
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String N = "100111";
        convertBase(N);
    }
}
 
// This code is contributed by Taranpreet


Python3




# Python code for the above approach
 
# Program to convert the base of
# given binary number to base 6
 
 
def convertBase(N):
 
    # 128 bit integer to store
    # the decimal conversion
    decimal = 0
 
    # Loop to iterate N
    for i in range(len(N)):
 
        # Binary to decimal
        decimal = decimal * 2 + (ord(N[i]) - ord('0'))
 
    # Stores the base 6 int
    ans = []
 
    # Decimal to base 6
    while (decimal > 0):
        ans.append(decimal % 6)
        decimal = decimal // 6
 
    # Print Answer
    for i in range(len(ans) - 1, -1, -1):
        print(ans[i], end="")
 
 
# Driver Code
N = "100111"
convertBase(N)
 
# This code is contributed by gfgking


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Program to convert the base of
    // given binary number to base 6
    public static void convertBase(string N)
    {
 
        // 128 bit integer to store
        // the decimal conversion
        int decimall = 0;
 
        // Loop to iterate N
        for (int i = 0; i < N.Length; i++) {
            // Binary to decimal
            decimall = decimall * 2 + (N[i] - '0');
        }
 
        // Stores the base 6 int
        List<int> ans = new List<int>();
 
        // Decimal to base 6
        while (decimall > 0) {
            ans.Add(decimall % 6);
            decimall = decimall / 6;
        }
 
        // Print Answer
        for (int i = ans.Count - 1; i >= 0; i--) {
            Console.Write(ans[i]);
        }
    }
 
    // Driver Code
    public static void Main()
    {
        string N = "100111";
        convertBase(N);
    }
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
        // JavaScript code for the above approach
 
        // Program to convert the base of
        // given binary number to base 6
        function convertBase(N)
        {
         
            // 128 bit integer to store
            // the decimal conversion
            let decimal = 0;
 
            // Loop to iterate N
            for (let i = 0; i < N.length; i++)
            {
             
                // Binary to decimal
                decimal = decimal * 2 +
                (N[i].charCodeAt(0) -
                '0'.charCodeAt(0));
            }
 
            // Stores the base 6 int
            let ans = [];
 
            // Decimal to base 6
            while (decimal > 0) {
                ans.push(decimal % 6);
                decimal = Math.floor(decimal / 6);
            }
 
            // Print Answer
            for (let i = ans.length - 1; i >= 0; i--) {
                document.write(ans[i]);
            }
        }
 
        // Driver Code
        let N = "100111";
        convertBase(N);
 
       // This code is contributed by Potta Lokesh
    </script>


 
 

Output

103

 

Time Complexity: O(len(N))
Auxiliary Space: O(1)

 

Another Approach: The given problem can also be solved by maintaining the integer in base 6 in place of the decimal conversion while converting the base of the binary integer to decimal. It is known that the binary number can be converted to a decimal using the following steps:

 

N = “1001”
N can be converted to (N)10 with the equation: (((1*2 + 0) *2 + 0) *2) + 1).

 

Hence, two types of steps are required, multiplying the integer by 2 which is equivalent to adding the integer in itself, and adding 0 or 1 to the integer as (0, 1)2 is equivalent to (0, 1)6. Hence, maintain a string representing a base 6 integer, and in each step, add the integer to itself and add 0 or 1 accordingly in each step. If can be done using the approach discussed here.

 

Below is the implementation of the above approach:

 

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the sum of
// two integers of base B
string sumBaseB(string a, string b, int base)
{
    int len_a, len_b;
 
    len_a = a.size();
    len_b = b.size();
 
    string sum, s;
    s = "";
    sum = "";
 
    int diff;
    diff = abs(len_a - len_b);
 
    // Padding 0 in front of the
    // number to make both numbers equal
    for (int i = 1; i <= diff; i++)
        s += "0";
 
    // Condition to check if the strings
    // have lengths mis-match
    if (len_a < len_b)
        a = s + a;
    else
        b = s + b;
 
    int curr, carry = 0;
 
    // Loop to find the find the sum
    // of two integers of base B
    for (int i = max(len_a, len_b) - 1; i > -1; i--) {
        // Current Place value for
        // the resultant sum
        curr = carry + (a[i] - '0') + (b[i] - '0');
 
        // Update carry
        carry = curr / base;
 
        // Find current digit
        curr = curr % base;
 
        // Update sum result
        sum = (char)(curr + '0') + sum;
    }
    if (carry > 0)
        sum = (char)(carry + '0') + sum;
    return sum;
}
 
// Program to convert the base of
// given binary number to base 6
string convertBase(string N)
{
    // Stores the required answer
    string ans = "0";
 
    // Loop to iterate N
    for (int i = 0; i < N.length(); i++) {
        // Multiply the current
        // integer with 2
        ans = sumBaseB(ans, ans, 6);
 
        // Add N[i] to ans
        ans = sumBaseB(ans, (N[i] == '0')
                                ? "0"
                                : "1",
                       6);
    }
 
    // Return Answer
    return ans;
}
 
// Driver Code
int main()
{
    string N = "100111";
    cout << convertBase(N);
 
    return 0;
}


Java




// Java program of the above approach
 
class GFG{
 
// Function to find the sum of
// two integers of base B
static String sumBaseB(String a, String b, int base)
{
    int len_a, len_b;
 
    len_a = a.length();
    len_b = b.length();
 
    String sum, s;
    s = "";
    sum = "";
 
    int diff;
    diff = Math.abs(len_a - len_b);
 
    // Padding 0 in front of the
    // number to make both numbers equal
    for (int i = 1; i <= diff; i++)
        s += "0";
 
    // Condition to check if the Strings
    // have lengths mis-match
    if (len_a < len_b)
        a = s + a;
    else
        b = s + b;
 
    int curr, carry = 0;
 
    // Loop to find the find the sum
    // of two integers of base B
    for (int i = Math.max(len_a, len_b) - 1; i > -1; i--) {
        // Current Place value for
        // the resultant sum
        curr = carry + (a.charAt(i) - '0') + (b.charAt(i) - '0');
 
        // Update carry
        carry = curr / base;
 
        // Find current digit
        curr = curr % base;
 
        // Update sum result
        sum = (char)(curr + '0') + sum;
    }
    if (carry > 0)
        sum = (char)(carry + '0') + sum;
    return sum;
}
 
// Program to convert the base of
// given binary number to base 6
static String convertBase(String N)
{
    // Stores the required answer
    String ans = "0";
 
    // Loop to iterate N
    for (int i = 0; i < N.length(); i++) {
        // Multiply the current
        // integer with 2
        ans = sumBaseB(ans, ans, 6);
 
        // Add N[i] to ans
        ans = sumBaseB(ans, (N.charAt(i) == '0')
                                ? "0"
                                : "1",
                       6);
    }
 
    // Return Answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    String N = "100111";
    System.out.print(convertBase(N));
 
}
}
 
// This code contributed by shikhasingrajput


Python3




# Python program of the above approach
 
# Function to find the sum of
# two integers of base B
def sumBaseB(a, b, base):
  len_a = len(a);
  len_b = len(b);
 
  s = ""
  sums = ""
 
  diff = abs(len_a - len_b)
 
  # Padding 0 in front of the
  # number to make both numbers equal
  for i in range(1, diff + 1):
    s += "0"
     
  # Condition to check if the strings
  # have lengths mis-match
  if (len_a < len_b):
    a = s + a
  else:
    b = s + b
 
  curr, carry = 0, 0
 
  # Loop to find the find the sum
  # of two integers of base B
  i = max(len_a, len_b) - 1
  while (i > -1):
    curr = carry + int(a[i]) + int(b[i])
    carry = int(curr / base)
    curr = curr % base
    sums = str(curr) + sums
    i -= 1
     
  if carry > 0:
    sums = str(carry) + sums
     
  return sums
 
# function to convert base of binary num to base 6
def convertBase(N):
  ans = ""
  for i in range(0, len(N)):
    ans = sumBaseB(ans, ans, 6)
    ans = sumBaseB(ans, ["1", "0"][N[i] == "0"], 6)
  return ans
 
N = "100111"
print(convertBase(N))
 
# This code is contributed by phalasi.


C#




// C# program of the above approach
using System;
class GFG{
 
  // Function to find the sum of
  // two integers of base B
  static string sumBaseB(string a, string b, int base1)
  {
    int len_a, len_b;
 
    len_a = a.Length;
    len_b = b.Length;
 
    string sum, s;
    s = "";
    sum = "";
 
    int diff;
    diff = Math.Abs(len_a - len_b);
 
    // Padding 0 in front of the
    // number to make both numbers equal
    for (int i = 1; i <= diff; i++)
      s += "0";
 
    // Condition to check if the Strings
    // have lengths mis-match
    if (len_a < len_b)
      a = s + a;
    else
      b = s + b;
 
    int curr, carry = 0;
 
    // Loop to find the find the sum
    // of two integers of base B
    for (int i = Math.Max(len_a, len_b) - 1; i > -1; i--) {
      // Current Place value for
      // the resultant sum
      curr = carry + (a[i] - '0') + (b[i] - '0');
 
      // Update carry
      carry = curr / base1;
 
      // Find current digit
      curr = curr % base1;
 
      // Update sum result
      sum = (char)(curr + '0') + sum;
    }
    if (carry > 0)
      sum = (char)(carry + '0') + sum;
    return sum;
  }
 
  // Program to convert the base of
  // given binary number to base 6
  static string convertBase(string N)
  {
    // Stores the required answer
    string ans = "0";
 
    // Loop to iterate N
    for (int i = 0; i < N.Length; i++) {
      // Multiply the current
      // integer with 2
      ans = sumBaseB(ans, ans, 6);
 
      // Add N[i] to ans
      ans = sumBaseB(ans, (N[i] == '0')
                     ? "0"
                     : "1",
                     6);
    }
 
    // Return Answer
    return ans;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    string N = "100111";
    Console.WriteLine(convertBase(N));
 
  }
}
 
// This code is contributed by ukasp.


Javascript




// JS program of the above approach
 
// Function to find the sum of
// 2 integers of base B
function sumBaseB(a, b, base)
{
    var len_a = a.length;
    var len_b = b.length;
     
    var s = "";
    var sums = "";
     
    var diff = Math.abs(len_a - len_b);
     
    // Padding 0 in front of the number to
    // make the both numbers equal
    for (var i = 1; i <= diff; i++)
    {
        s += "0";
    }
     
    // condition to check if the strings
    // have mismatch in lengths
    if (len_a < len_b)
    {
        a = s + a;
    }
    else
    {
        b = s + b;
    }
     
    var curr = 0;
    var carry = 0;
     
    // loop to find the sum of 2
    // integers of base B
     
    var i = Math.max(len_a, len_b) - 1
    while (i > -1)
    {
        curr = carry + parseInt(a[i]) + parseInt(b[i]);
        carry = parseInt(curr / base);
        curr %= base;
        sums = String(curr) + sums;
        i--;
    }
     
    if (carry > 0)
        sums = String(carry) + sums;
         
    return sums;
}
 
// function to convert base 2 number to base 6
function convertBase(N)
{
    let ans = "";
    for (var i = 0; i < N.length; i++)
    {
        ans = sumBaseB(ans, ans, 6);
        ans = sumBaseB(ans, (N[i] == "0") ? "0" : "1", 6);
    }
    return ans;
}
 
// Driver code
let N = "100111";
document.write(convertBase(N));
 
//This code is contributed by phasing17.


 
 

Output

103

 

Time Complexity: O(len(N)2)
Auxiliary Space: O(len(N))

 

Note that the complexity of 1st approach is less than the second approach but the first approach can only handle binary integers up to 127 bits while the second approach can handle much larger values as well.

 



Last Updated : 01 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads