📌  相关文章
📜  将一个以 2 为底的数字转换为以 6 为底的数字

📅  最后修改于: 2022-05-13 01:56:09.144000             🧑  作者: Mango

将一个以 2 为底的数字转换为以 6 为底的数字

给定一个二进制整数N ,任务是将其转换为基数 6。

注意:N 中的位数最多为 100。

例子:

方法:给定问题可以通过首先将给定整数转换为十进制,然后使用此处讨论的方法将数字从十进制转换为基数6来解决。请注意,由于N的值可以达到 2 100 ,因此可以使用 128 位整数来存储十进制数。

下面是上述方法的实现:

C++
// C++ program of the above approach
#include 
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 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 
#include 
#include 
 
// 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 ans = new ArrayList();
 
        // 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 ans = new List();
 
        // 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


C++
// C++ program of the above approach
#include 
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.



输出
103

时间复杂度: O(len(N))
辅助空间: O(1)

另一种方法:给定的问题也可以通过保持以 6 为基数的整数代替十进制转换同时将二进制整数的基数转换为十进制来解决。众所周知,可以使用以下步骤将二进制数转换为十进制数:

因此,需要两种类型的步骤,将整数乘以 2 相当于将整数本身相加,以及将 0 或 1 加到整数上,因为 (0, 1) 2相当于 (0, 1) 6 。因此,维护一个表示以 6 为基数的整数的字符串,并在每一步中,将整数添加到自身,并在每一步中相应地添加 0 或 1。如果可以使用此处讨论的方法来完成。

下面是上述方法的实现:

C++

// C++ program of the above approach
#include 
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.


输出
103

时间复杂度: O(len(N) 2 )
辅助空间: O(len(N))

请注意,第一种方法的复杂性低于第二种方法,但第一种方法只能处理高达 127 位的二进制整数,而第二种方法也可以处理更大的值。