Hello. Is there something wrong with my logic? The results are wrong and I can't find errors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//the string is supposed to be binary code.
int to_decimal(string s)
{
int sum = 0;
int counter = 0;
for (int i = 0; i<s.length(); i++)
{
if (s[i] =='1')
{
counter++;
}
}
for (int i = 0; i < counter; i++)
{
sum += pow(2, i);
}
return sum;
}
There are so many things wrong with the logic, you should start over and try another approach.
First of all, suppose I had the binary number 100, which is 4 in decimal. In your function, counter would become 1, in your loop,
sum += 2^0
sum += 2^1
which gives 3. The logic behind your second loop is obviously wrong.
Another example, suppose I had 110. That means counter becomes 2. But wait, what if I had 101? The counter also becomes 2. The logic behind your first loop is also wrong.
int to_decimal(string s)
{
int sum = 0;
reverse(s.begin(), s.end());
for (int i = 0; i<s.length(); i++)
{
if (s[i] =='1')
{
sum += pow(2, i);
}
}
return sum;
}