Print a number converted in base 2 recursively

Viewed 154

So I've been trying to do this but I just can't think of a solution for this. I've got this bit of code but it outputs it backwards(if the answer is 11110 I get 01111):

#include <stdio.h>

int base(int n)
{
    if(n==0)
        return 0;
    else
    {
        printf("%d",n%2);
    }
    return base(n/2);


}
int main() {
    int n;
    scanf("%d",&n);
    base(n);
    return 0;
}

Is there any trick for this problem or do I need to analyze this deeper?

2 Answers

As @rici stated, a very simple fix is to print after the recursive call:

#include <stdio.h>

void base(int n){
    if(n==0)
        return;
    base(n/2);
    printf("%d",n%2);
}

int main() {
    int n;
    scanf("%d",&n);
    base(n);
    return 0;
}

I would use a mask:

#include <stdio.h>

int base(int n, int mask){
    if(!mask) {
        printf("\n"); // we reach the end, print a line return
        return 0;
    }
    printf("%d",  !!(n & mask)); // if mask and n match, print '1', else print '0'. !! convert any value into 1, and 0 remains 0.
    return base(n, mask >> 1); // divide mask by 2, check the next bit on the right
}

int main() {
    int n;
    scanf("%d",&n);
    base(n, 1 << (31 - __builtin_clz(n))); // call the function with a mask initialized at the same level than the most important bit of n. 
    return 0;
}
Related