【问题标题】:Print a number converted in base 2 recursively以递归方式打印以 2 为底数转换的数字
【发布时间】:2021-06-05 18:55:25
【问题描述】:

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

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

【问题讨论】:

  • 不是按照处理顺序(从右到左)打印数字,而是传递一个缓冲区,您可以在其中以正确的顺序填写这些数字。然后在最后打印。
  • 在递归调用之后打印,而不是之前。
  • 我会使用掩码以避免有缓冲区,请参阅我的回答
  • Rares Amza,n &lt; 0 时应该打印什么?当n== 0?
  • 感谢有用的提示,通话后打印的提示也将非常有用@chux-ReinstateMonica 我不太关心n&lt;0n==0时的情况应该只打印0 我猜因为这就是你在base 2中表示它的方式

标签: c base


【解决方案1】:

我会使用面具:

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

【讨论】:

  • __builtin_clz(n) 不是 C 的一部分。此答案假定选择编译器和 int 范围。 1 &lt;&lt; 31 的转变也是一个问题。
【解决方案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;
}

【讨论】:

  • 换行怎么办?
  • mm 我想一个简单的包装器可以解决这个问题!
  • 注意:base(0) 不打印任何内容。
  • base(-7) 打印“-1-1-1”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多