【发布时间】:2017-06-19 04:35:45
【问题描述】:
所以我被要求编写一个将二进制数转换为十进制数的程序。在这种情况下,它是 10111。我遇到的问题是我不允许使用 math.pow,所以我必须使用嵌套循环。这是我目前所拥有的。
public static void main(String[] args) {
int x = 10111;
int num = 0, counter = 0;
for (int i = 1; i <= x; i *= 10) {
int binaryDigit = x/i%10;
num += (int) (Math.pow(2, counter) * binaryDigit);
counter++;
}
System.out.println("\""+ x + "\" in binary is equivalent to " + num + " in decimal");
}
【问题讨论】:
-
你也可以通过乘以loop.2 power 5 =2*2*2*2*2
-
@luk2302 代码有效,但我的问题是我想用循环替换 math.pow 的东西。
-
@FastSnail 确实如此。由于问题代码中的循环以最低有效数字开头,因此实际上可以在同一循环内计算功率。 (正如我的回答所做的那样)
-
一个非常缓慢、糟糕和懒惰的解决方案:
num = Integer.parseInt(Integer.toString(x), 2);。使用过的库不使用Math.pow(),但我不确定是否允许您使用它们。否则你可以自己写一个 pow() 函数。
标签: java