-1

I'm trying to make a function which converts a number to binary in C++ but whenever I call the function it returns an empty string.

Here is my code:

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <math.h>
#include <algorithm>

using namespace std;

string dec2bin(long long x, vector<long long> extra = { }) {

    string out;
    string output;
    int i = 0;
    long long sum = 0;
    bool ok = false;

    if(!extra.empty()) {
        for(int a = 0; a < extra.end() - extra.begin(); a++) {
            sum += pow(2, extra[a]);
        }
    }

    while(pow(2, i) + sum < x) {
        i++;
    }
    if(i > 0) {
        i--;
    }
    extra.push_back(i);

    if(pow(2, i) + sum == x) {

        long long max = *max_element(extra.begin(), extra.end());

        for(int a = max; a >= 0; a--) {
            if(std::find(extra.begin(), extra.end(), a) < extra.end()) {
                out += '1';
            }
            else {
                out += '0';
            }
        }
        ok = true;
    }

    if(ok) {
        return out;
    }
    else {
        dec2bin(x, extra);
    }
}

int main() {

    long long a;
    cin >> a;

    cout << dec2bin(a) << endl;

    return 0;

}

If I add a line containing cout << out << endl; before the return statement, it prints out the string. Any help is much appreciated :)

  • You shouldn't use `pow`. You are potentially going to lose digits, since `pow` returns a double, and you're potentially storing a `double` into a `long long`. Turn up your warning level on your compiler. – PaulMcKenzie Mar 26 '16 at 00:39
  • Also, see this concerning using `pow` for integer usage: http://stackoverflow.com/questions/25678481/why-pown-2-return-24-when-n-5 – PaulMcKenzie Mar 26 '16 at 01:06

1 Answers1

0

Under else change dec2bin(x, extra); to:

   return dec2bin(x, extra);

I think that's your problem.

DimChtz
  • 4,043
  • 2
  • 21
  • 39