everyone ! Now I am stuck here with a problem...
Problem:
Given a binary number represented as an array, write a function that takes the array and its size as a parameter, and returns the integer value. You may assume that there are at least 1 and no more than 30 numbers in the array and that all the values are either 0 or 1. The array is ordered with most significant binary digit at the start (index 0) and the least significant digit at the end.
Signature: int binary_to_number(int binary_digits[], int number_of_digits)
The function I have wrote is at the bottom. It works fine to return the int value for number_of_digits <= 10.
As you can see, that the question says "You may assume that there are at least 1 and no more than 30 numbers in the array"
My question is, how can I fix my function to return proper int value even if there is more than 10 numbers (perhaps 30 numbers)?
OR, Should I be approaching the problem different way? and if so, what should I do?
#include<iostream>
#include<string>
int binary_to_number(int binary_digits[], int number_of_digits){
std::string bin_str;
for (int i=0; i<number_of_digits; i++) {
if (binary_digits[i] == 0) {
bin_str = "0" + bin_str;
} else if (binary_digits[i] == 1) {
bin_str = "1" + bin_str;
}
}
int bin_int = std::stoi (bin_str);
return bin_int;
}