添加二进制数

2022-09-02 11:05:49

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

例如。1010 + 10 = 1100


答案 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;
}

答案 2

要深入了解基础知识:

public static String binaryAddition(String s1, String s2) {
    if (s1 == null || s2 == null) return "";
    int first = s1.length() - 1;
    int second = s2.length() - 1;
    StringBuilder sb = new StringBuilder();
    int carry = 0;
    while (first >= 0 || second >= 0) {
        int sum = carry;
        if (first >= 0) {
            sum += s1.charAt(first) - '0';
            first--;
        }
        if (second >= 0) {
            sum += s2.charAt(second) - '0';
            second--;
        }
        carry = sum >> 1;
        sum = sum & 1;
        sb.append(sum == 0 ? '0' : '1');
    }
    if (carry > 0)
        sb.append('1');

    sb.reverse();
    return String.valueOf(sb);
}