vendredi 10 avril 2020

Is there any faster way to solve this problem?

Write and test your own double abc (char * b) function in the program, taking in the form of a string the fractional binary number of the form "1101.101" and returning an equal decimal number (here 1 * 2 ^ 3 + 1 * 2 ^ 2 + 0 * 2 ^ 1 + 1 * 2 ^ 0 + 1 * 2 ^ -1 + 0 * 2 ^ -2 + 1 * 2 ^ -3 = 8 + 4 + 0 + 1 + 0.5 + 0 + 0.125 = 13.625). The function should return the special value -1 if an incorrect fractional binary number is entered (e.g. containing a different digit than 0, 1 or more than one period '.').

My solution:

#include <iostream>
#include <cmath>
using namespace std;
double abc(char* b);
int main() {
cout <<  abc("1101.101");
return 0;
}

double abc(char* b){
int i = 0;
int a = 0;
int dot = 0;
double sum=0;
int c = 0;
do{
    if ((b[a]=='1')||(b[a]=='0')||(b[a]=='.')){
        a++;
        if(b[a]=='.'){
            dot++;
        }
        if(dot==2){
            return -1;
        }
    } else {
        return -1;
    }
} while(b[a]!='\0');

while(b[i]!='.'){
    i++;
}
while(i!=0) {
    if(b[c]=='1'){
        sum = sum + pow (2, i-1);
    }
    c++;
    i--;
}
while(b[i]!='.'){
    i++;
}
if(b[i]=='.'){
    int m = 0;
    while(b[i]!='\0'){
        if(b[i]=='1'){
            sum = sum + pow (2, m);
        }
        m = m - 1;
        i++;
    }
}
return sum;
}

Problem: Everything is fine, it gives me 13.625, but there is a lot of code. Is there any faster way to solve this exercise?

Aucun commentaire:

Enregistrer un commentaire