一尘不染

加二进制数

java

有谁知道如何在Java中添加两个以二进制形式输入的二进制数字?

例如,1010 + 10 = 1100


阅读 261

收藏
2020-09-08

共1个答案

一尘不染

使用Integer.parseInt(String, int radix)

 public static String addBinary(){
 // The two input Strings, containing the binary representation of the two values:
    String input0 = "1010";
    String input1 = "10";

    // Use as radix 2 because it's binary    
    int number0 = Integer.parseInt(input0, 2);
    int number1 = Integer.parseInt(input1, 2);

    int sum = number0 + number1;
    return Integer.toBinaryString(sum); //returns the answer as a binary value;
}
2020-09-08