-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 :)

2
  • 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. Commented Mar 26, 2016 at 0:39
  • Also, see this concerning using pow for integer usage: stackoverflow.com/questions/25678481/… Commented Mar 26, 2016 at 1:06

1 Answer 1

0

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

   return dec2bin(x, extra);

I think that's your problem.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.