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

时间:2021-03-07 19:32:57

标签: c base

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

这个问题有什么技巧吗,或者我需要更深入地分析这个问题吗?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:-2)

我会使用面具:

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