递归打印以 2 为基数转换的数字

Print a number converted in base 2 recursively

所以我一直在尝试这样做,但我就是想不出解决方案。我有这段代码,但它向后输出(如果答案是 11110,我得到 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;
}

这个问题有什么技巧吗,还是需要深入分析一下?

我会戴口罩:

#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;
}

@rici所述,一个非常简单的解决方法是在递归调用后打印:

#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;
}