簡體   English   中英

兩個二進制數的加法

[英]Addition of two binary numbers

我試圖通過將數字放入char數組來對每個數字進行補全,並使用if條件對每個數字進行補全。 應該覆蓋每個結果,並且應該將每個結果保存在String result但是整個操作的結果始終為空白。 Java調試器無法正常工作,我不明白為什么它無法正常工作。

import java.util.Scanner;

public class BinaryAdder {
    public static String add(String binary1, String binary2) {

        String result = "";
        char[] safea = binary1.toCharArray();
        char[] safeb = binary2.toCharArray();

        int lb1 = binary1.length() - 1;
        int lb2 = binary2.length() - 1;
        char reminder = 0;

        while (lb1 != 0 || lb2 != 0) {
            if (safea[lb1] == 0 && safeb[lb2] == 0 && reminder == 0) {
                result += "0";
                lb1--;
                lb2--;
            } else if (safea[lb1] == 1 && safeb[lb2] == 0 && reminder == 0) {
                result += "1";
                lb1--;
                lb2--;
            } else if (safea[lb1] == 1 && safeb[lb2] == 1 && reminder == 0) {
                result += "0";
                reminder = 1;
                lb1--;
                lb2--;
            } else if (safea[lb1] == 1 && safeb[lb2] == 1 && reminder == 1) {
                result += "1";
                reminder = 1;
                lb1--;
                lb2--;
            } else if (safea[lb1] == 1 && safeb[lb2] == 0 && reminder == 1) {
                result += "0";
                reminder = 1;
                lb1--;
                lb2--;
            } else if (safea[lb1] == 0 && safeb[lb2] == 1 && reminder == 1) {
                result += "0";
                reminder = 1;
                lb1--;
                lb2--;
            } else if (safea[lb1] == 0 && safeb[lb2] == 1 && reminder == 0) {
                result += "1";
                lb1--;
                lb2--;
            } else if (safea[lb1] == 0 && safeb[lb2] == 0 && reminder == 1) {
                result += "1";
                lb1--;
                lb2--;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Summand:  ");
        String input1 = scan.next("(0|1)*");
        System.out.print("Summand:  ");
        String input2 = scan.next("(0|1)*");
        scan.close();
        System.out.println("Result: " + add(input1, input2));
    }

}

您可以使用Integer.parseInt(s, radix)將這些位解析為整數。 您需要使用2的基數:

public static String add(String binary1, String binary2) {
    int i1 = Integer.parseInt(binary1, 2);
    int i2 = Integer.parseInt(binary2, 2);
    return Integer.toBinaryString(i1 + i2);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM