Mamba
Mamba

Reputation: 43

Why is my answer off for certain values of binary representation provided?

The question basically asks us to convert the input binary string (only 1 and 0 provided). Input format is as follows (each separate point is a new line):

My code:

#include <iostream>
#include <cmath>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int len;
        cin >> len;
        long long num = 0;
        while(len--){
            char digit;
            cin >> digit;
            num += (digit-'0')*pow(2,len);
        }
        cout << num << endl;
    }
    return 0;
}

Ik there are other methods to go about this problem, but i want to know whats the problem in mine. Inputting certain values like '10001011111110111010111011010011011011110001011000011101' gives an answer '39401750052935200' when the correct value is '39401750052935197'.

Other examples of wrong output:

My code runs correct for all smaller values of binary input (of length maybe less than 50). Why does it fail for such larger values by such a small margin?

Upvotes: 2

Views: 72

Answers (1)

chux
chux

Reputation: 154255

runs correct for all smaller values of binary input (of length maybe less than 50).

num += (digit-'0')*pow(2,len); is like

num = num + (digit-'0')*pow(2,len);

and the addition is done using double math with its 53-ish bit precision infected by pow().


Instead only use integer math:

unsigned long long num = 0;
...
  num = num*2 + (digit-'0');

Upvotes: 3

Related Questions