📜  二进制到十进制的递归程序

📅  最后修改于: 2021-05-31 16:32:37             🧑  作者: Mango

给定一个二进制数字作为字符串,找到其十进制等效项。

例子:

Input :  binary = "101"
Output :   5

Input :  binary = "1111"
Output :   15

我们讨论了将二进制转换为十进制的迭代解决方案。

这个想法很简单,我们添加当前术语,然后重复其余术语。

二进制2十进制

C++
// Recursive CPP program to convert binary 
// decimal
#include
using namespace std;
  
int toDecimal(string binary, int i=0)
{
    // If we reached last character
    int n = binary.length();
    if (i == n-1)
      return binary[i] - '0';
      
    // Add current tern and recur for
    // remaining terms
    return ((binary[i] - '0') << (n-i-1))  +
            toDecimal(binary, i+1);
}
  
// Driver code
int main()
{
    string binary = "1010";
    cout << toDecimal(binary) << endl;
    return 0;
}


Java
// Recursive Java program to convert binary 
// decimal
  
  
class GFG
{
    static int toDecimal(String binary,int i)
    {
        // If we reached last character
        int n = binary.length();
        if (i == n-1)
        return binary.charAt(i) - '0';
          
        // Add current tern and recur for
        // remaining terms
        return ((binary.charAt(i) - '0') << (n-i-1)) +
                toDecimal(binary, i+1);
    }
      
    // Driver code
    public static void main(String []args)
    {
        String binary = "1010";
        int i=0;
        System.out.println(toDecimal(binary,i));
          
    }
  
}
  
// This code is contributed 
// by ihritik ( Hritik Raj)


Python3
# Recursive Python3 program to convert 
# binary decimal 
  
def toDecimal(binary, i = 0):
  
    # If we reached last character 
    n = len(binary) 
    if (i == n - 1) :
        return int(binary[i]) - 0
      
    # Add current tern and recur for 
    # remaining terms 
    return (((int(binary[i]) - 0) << (n - i - 1)) + 
                        toDecimal(binary, i + 1))
  
# Driver code 
if __name__ == "__main__" :
      
    binary = "1010"
    print(toDecimal(binary))
  
# This code is contributed by Ryuga


C#
// Recursive C# program to convert binary 
// decimal
  
  
using System;
class GFG
{
    static int toDecimal(string binary, int i=0)
    {
        // If we reached last character
        int n = binary.Length;
        if (i == n-1)
        return binary[i] - '0';
          
        // Add current tern and recur for
        // remaining terms
        return ((binary[i] - '0') << (n-i-1)) +
                toDecimal(binary, i+1);
    }
      
    // Driver code
    public static void Main()
    {
        string binary = "1010";
        Console.WriteLine(toDecimal(binary));
          
    }
  
}
  
// This code is contributed 
// by ihritik ( Hritik Raj)


PHP


输出:
10
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”