在 Java 中使用模数运算符将用户输入从二进制转换为十进制

Converting user input from binary to decimal using Modulus Operator in Java

我很难找到编程 1 class 作业的答案。分配提示用户输入二进制(最多 4 位),并将其转换为十进制等效值。不允许使用循环、条件语句、ParseInt 以及模运算符和其他数学运算符以外的任何内容。

我在数学方面遇到了问题,我想一旦我理解了如何使用模数运算符来回答问题,我就能够为其编写代码。

我进行了搜索,但未能找到任何有用的信息。

您应该获取每个位置的数值并使用 2 的幂将它们相加以返回原始数值。

    double num = 1110;
    double ones = Math.floor(num % 10);
    double tens = Math.floor(num/10 % 10);
    double hundreds = Math.floor(num/100 % 10);
    double thousands = Math.floor(num %10000 /1000);
    double tenThousands = Math.floor(num / 10000 % 10);

    double original = (ones * 1) +
                      (tens * 2) + 
                      (hundreds * 4) +
                      (thousands * 8);


    System.out.println(num);
    System.out.println("ones: " +ones);
    System.out.println("tens: " +tens);
    System.out.println("hundreds: " +hundreds);
    System.out.println("thousands: " + thousands);
    System.out.println("original number : " + original);