I've been on this homework problem for about 2 hours and I just can't wrap my mind around it. It is driving me frickin' crazy.....
So here's the question: Write a function that takes an integer value n whose all of its digits are zeros and/or ones and returns the corresponding decimal value, test the function. (use the function intPow ( ) developed in Question 4 above).
Here's my failed 2hour effort:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

#include<iostream>
using namespace std;
int b2d(int a);
void main()
{
int a;
cout<<"Enter a binary number and its number of digits to find the decimal: ";
cin>>a;
cout<<"In decimal, "<<a<<"="<<b2d(a)<<endl;
}
int b2d(int a){
int tot=0;
int two=1;
for(int i=0;i<3;i++){
two=two*2;
for(a;a>0;a=a/10){
a=a%10;
}
tot=tot+(a*two);
}
return tot;
}
 
This is the code he was referring to from Question4 (which I solved):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

#include<iostream>
using namespace std;
int intPow(int x,int n);
void main()
{
int x,n;
cout<<"Enter two integers x,n, to compute x^n: ";
cin>>x>>n;
cout<<x<<"^"<<n<<"= "<<intPow(x,n)<<endl;
}
int intPow(int x,int n){
int tot=1;
for(int i=0;i<n;i++){
tot=tot*x;
}
return tot;
}
 
Basically, In my answer, I tried using methods from two programs to make the converter work. I used a loop to isolate each number of the binary digit alone, like 1101 would be handled as 1, 1, 0 and 1. and the other for doing the calculation of converting.
Basically what I'm failing at is doing this:
decimal =1*2^0 + 0*2^1 + 1*2^2 + 1*2^3 = 13
The isolation idea i'm trying to use is from code i used two days ago:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

#include<iostream>
using namespace std;
int digitSum(int a);
void main()
{
int a;
cout<<"Enter a integer: ";
cin>>a;
cout<<"The sum of "<<a<<"'s digits is: "<<digitSum(a)<<endl;
}
int digitSum(int a){
int tot=0;
for(a;a>0;a=a/10){
tot=tot+a%10;
}
return tot;
}
 
Guys I simply can't find a solution to this. Please help me and aim me in the right direction..........