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

问题描述

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

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

解决方法

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

我会使用面具:

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...