java - 描述用于十进制到二进制转换的此函数

标签 java c++ c

我无法理解为什么它打印总二进制位而不是 Java 和 C++ 中的最后一位。我在 C 中检查了它,因为我认为它只显示最后一位。但是,在 C++ 和 Java 中,它会打印所有位。

public static void main(String[] args) {

    toBin(2);
}// end of main

static void toBin(int b) {
    int modu = 0;

    if (b < 1) {
        return;
    }
    modu = b % 2;
    b=(b>>1);
    toBin(b);
    System.out.print(modu);       

}// end of toBin()

最佳答案

这段代码应该在所有三种语言中做同样的事情:它递归地打印一个数字的所有位。

让我们研究一下当您在数字 5 上调用 toBin 时会发生什么:

modu of the first level of invocation is set to 1 (5%2)
    toBin is called on 2 (5>>1)
    modu of the second level of invocation is set to 0 (4%2)
    toBin is called on 1 (2>>1)
        modu of the third level of invocation is set to 1 (1%2)
        toBin is called on 0 (1>>1)
             toBin returns because b < 1
        modu of the third level is printed: 1; toBin returns
     modu of the second level is printed: 0; toBin returns
 modu of the first level is printed: 1; toBin returns

作为结果,101,即 5 的二进制表示,被打印出来。

关于java - 描述用于十进制到二进制转换的此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9010615/

相关文章:

java - 如何防止 java.lang.NumberFormatException : For input string: "N/A"?

java - 在@Configuration或@Component中定义@Bean

c++ - qt designer 指定的 QDialog 的 valgrind 问题

c++ - 使用 c++ 和 glfw 的 raii 架构

java - 在 Java 中将方法标记为纯函数的约定

java - 使用 AWS Java SDK 在 AWS Redshift 中创建表

c++ - 为什么在调用 glDrawArrays 之前不需要绑定(bind)顶点缓冲区对象?

objective-c - %qx 格式说明符是什么意思

子程序中的 C Hello World 程序

c++ - 负数的strtoul