2

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?

Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81
Rares Amza
  • 83
  • 5
  • 1
    Rather than printing the digits in the order they're processed (right to left), pass a buffer around where you can fill in those digits in the correct order. Then print at the end. – Jeff Mercado Mar 07 '21 at 19:37
  • 2
    Print after the recursive call, not before. – rici Mar 07 '21 at 19:44
  • 1
    I would use a mask in order to avoid having a buffer, see my answer – Antonin GAVREL Mar 07 '21 at 19:53
  • Rares Amza, What should print when `n < 0`? When `n== 0`? – chux - Reinstate Monica Mar 07 '21 at 21:26
  • thanks for the useful tips, also the one with printing after the call will be very useful @chux-ReinstateMonica I didn't really care about the case when ```n<0```, and when ```n==0``` it should print just ```0``` I guess since that is how you represent it in base 2 – Rares Amza Mar 08 '21 at 13:24
  • @RaresAmza With "I didn't really care about the case when n<0, and when n==0 it should print just 0", accepted answer `base(-11)` as `"-10-1-1"` is OK and `base(0)` prints nothing. Interesting. UV for explaining your goals yet disagree with them. – chux - Reinstate Monica Mar 08 '21 at 13:39
  • @chux-ReinstateMonica I will revisit this soon to try and make it work 100% – Rares Amza Mar 09 '21 at 09:19

2 Answers2

2

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;
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
-2

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;
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81