Write a recursive function it should take as a parameter a
Write a recursive function - it should take as a parameter a C++ string of \'1\'s and \'0\'s that are the binary representation of a positive integer, and return the equivalent int value. The function should be named binToDec. Do not use any number base conversion functionality that is built into C++. Do not use any loops. The file must be named: converter.cpp
Solution
Here is method:
int binToDec(string binary,int i = 0)
{
// i holds the current position of string
int tot = 0;
int index = 0;
if (i < binary.length())
{
// check if it is 1
if (binary[i] == \'1\')
{
//calculate the index position to pow
index = binary.length() - i -1;
tot = pow(2, index);
}
return tot + binToDec(binary, ++i);
}
return tot;
}
Here is sample code to test:
#include <iostream>
#include <math.h>
using namespace std;
int binToDec(string binary,int i = 0)
{
// i holds the current position of string
int tot = 0;
int index = 0;
if (i < binary.length())
{
// check if it is 1
if (binary[i] == \'1\')
{
//calculate the index position to pow
index = binary.length() - i -1;
tot = pow(2, index);
}
return tot + binToDec(binary, ++i);
}
return tot;
}
int main()
{
// calling binToDec()
int result = binToDec(\"10011\");
cout << result << endl;
return 0;
}
Output:
19
