public class BinaryToDecimal{
public static void main(String[]args){
int binary = 101011101;
int d = 10;
int l = 1;
for (int j=1;j<=8;j++){
int r = (binary/d%10)*l;
int k = r;
int z = r + k;
d*=10;
l*=2;
}
System.out.println("The binary number " + binary + " is equivalent to "+ z +" in decimal."); // z here is out of scope of for
}
}
我只需要使用for循环完成这项任务,但我找不到工作代码......这是我做的最好的。
答案 0 :(得分:1)
这是一个使用2^x
逻辑的非常简单的算法。
它基本上做的是:
如果我们在二进制变量中遇到1
,我们会将2^(Position of the 1)
添加到decimal
变量
class MyClass{
public static void main(String[] args) {
int bin = 101;
String binary = String.valueOf(bin);
int decimal = 0;
for (int i = 0 ; i < binary.length() ; i++){
if (binary.charAt(i) == '1'){
decimal += Math.pow(2, binary.length() - i - 1);
}
}
System.out.println(decimal);
}
}
答案 1 :(得分:0)
public class BinaryToDecimal{
public static void main(String[]args){
int binary = 101011101;
int powerOfTen = 10;
int powerOfTwo = 1;
int Decimal = 0;
for (int j=1;j<=8;j++){
int splitAnswer = (binary/powerOfTen%10)*powerOfTwo;
int old = splitAnswer;
Decimal = splitAnswer + old;
powerOfTen*=10;
powerOfTwo*=2;
}
System.out.println("The binary number " + binary + " is equivalent to "+ Decimal +" in decimal.");
}
}