我正在创建一个简单的程序,将二进制数转换为十进制数,而不使用math.pow()
。这是我到目前为止所得到的,在最后使用 Math.pow
:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
System.out.println("Enter a binary number");
Scanner inputKeyboard = new Scanner(System.in);
String binaryNumber = inputKeyboard.nextLine();
while (!checkIfBinary(binaryNumber)) {
System.out.println("That is not a binary number. Enter a binary number");
binaryNumber = inputKeyboard.nextLine();
}
int decimalNumber = binaryToNumber(binaryNumber);
System.out.println("Your number in base 10 is " + decimalNumber + ".");
}
public static boolean checkIfBinary(String input) {
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
}
return true;
}
public static int binaryToNumber(String numberInput) {
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}
我在没有 math.pow
的情况下进行求幂时遇到问题。我知道我需要使用一个循环,并且这个循环应该将 2 乘以 numberInput.length() - 1 - i
次。但我在实现这一点时遇到了困难。
最佳答案
将您的String
解析为整数并为其提供基数2
int decimalValue = Integer.parseInt(yourStringOfBinary, 2);
但请记住,整数的最大值是2^31-1
,二进制表示为:
1111111111111111111111111111111
因此,如果您输入比上面更大的二进制值,您将收到 java.lang.NumberFormatException
错误,要解决此问题,请使用 BigInteger
,
int decimalValue = new BigInteger(yourBinaryString, 2).intValue()
关于java - 不使用 math.pow( ) 将二进制转换为基数 10?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28307352/