1. 程式人生 > >leetcode試題之二進位制加法--java實現

leetcode試題之二進位制加法--java實現

/*
本題的需求是:給出兩個字串,內容是二進位制數字,編寫計算兩個二進位制數字和的程式。
難點是考慮周到,尤其是最後的一個進位,容易遺忘。

*/


import java.util.ArrayList;
class AddBinary{
public static void main(String args[])
{
    AddBinary addBinary = new AddBinary();
    addBinary.AddBinary("11011","11101");

}
public String AddBinary(String a,String b)
{
    int aLength = a.length();
    int bLength = b.length();
    String result = ""; 
    ArrayList<Integer> aList = new ArrayList<Integer>();
    ArrayList<Integer> bList = new ArrayList<Integer>();

    for(int i =0;i<aLength;i++){
		aList.add(0,Integer.parseInt(a.substring(i,i+1)));

	}
	for(int j =0;j<bLength;j++){
		bList.add(0,Integer.parseInt(b.substring(j,j+1)));

	}
    

    int k =0;
    int plugnum =0;
    while(k<aLength && k<bLength)
    {
        int a1 = aList.get(k);
        int b1 = bList.get(k);

        int sum = a1 + b1 +plugnum;
        
        if(sum>=2)
        {
            sum = sum % 2;
            result = String.valueOf(sum)+result;
            plugnum = 1;
        }
        else
        {
            result = String.valueOf(sum)+result;
        }
        k++;
       
    }
    if(k<aLength)
    {
        int i =k;
        int a2 = aList.get(i);
        int sum = a2 + plugnum;
        if(sum>=2)
        {
            sum = sum % 2;
            result = String.valueOf(sum)+result;
            plugnum =1;
        }
        else
        {
            result = String.valueOf(sum)+result;
        }
        i++;
    }
    if(k<bLength)
    {   int i =k;
        int b2 = bList.get(i);
        int sum = b2 + plugnum;
        if(sum>=2)
        {
            sum = sum%2;
            result = String.valueOf(sum)+result;
            plugnum=1;

        }
        else
        {
            result = String.valueOf(sum)+result;
        }
        i++;
    }
    //這一段程式碼是最後的進位:
    if(plugnum == 1)
    {   
        result = String.valueOf(plugnum)+result;
    }
    System.out.println("二進位制數字的和是:");
    System.out.println(result);
    return result;
}

}
java AddBinary
二進位制數字的和是:
111000