java - 不使用 math.pow( ) 将二进制转换为基数 10?

标签 java math base-conversion

我正在创建一个简单的程序,将二进制数转换为十进制数,而不使用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/

相关文章:

java - 如何使用第一个 JSON 对象覆盖第二个 JSON 对象

java - 通过 https 和防火墙的 SOAP Spring 客户端请求

java - 从 fragment 返回 Activity 时调用函数

javascript - 如何在javascript中将数字数组中的值相乘?

python - 检测改变点时三角形是否翻转

javafx检查场景中是否存在对象

algorithm - 这个高斯消元伪代码的第一步是否正确?

php - 计算排列的因子秩(N 选择 K)

python - 十六进制十进制浮点Python