1. 程式人生 > >Add Binary 二進位制相加 @LeetCode

Add Binary 二進位制相加 @LeetCode

題目:

二進位制相加

思路:

處理好carry的情況

package Level2;

/**
 * Add Binary
 *
 * Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".
 */
public class S67 {

	public static void main(String[] args) {
		String a = "1111";
		String b = "1111";
		System.out.println(addBinary(a, b));
	}
	
	public static String addBinary(String a, String b) {
        int i = a.length() - 1;		// i指向a的末尾
        int j = b.length() - 1;		// j指向b的末尾
        int c = 0;		// carry 進位
        // 先把String轉為char陣列便於處理
        char[] achar = a.toCharArray();
        char[] bchar = b.toCharArray();
        // 結果陣列
        char[] reschar = new char[Math.max(achar.length, bchar.length)+2];
        int k = 0;		// k指向結果陣列的開頭
        
        while(true){
        	if(i<0 && j<0 && c==0){
        		break;
        	}
        	
        	int aint = 0;
        	int bint = 0;
        	
        	if(i >= 0){
        		aint = achar[i] - '0';
        	}
        	if(j >= 0){
        		bint = bchar[j] - '0';
        	}
        	if(aint + bint + c > 1){
        		reschar[k] = (char) ('0' + aint + bint + c - 2);
        		c = 1;
        	}else{
        		reschar[k] = (char) ('0' + aint + bint + c);
        		c = 0;
        	}
        	k++;
        	i--;
        	j--;
        }
         // char陣列轉string,然後翻轉
        return new StringBuffer(new String(reschar, 0, k)).reverse().toString();
    }

}
public class Solution {
     public static String addBinary(String a, String b) {
        int len = Math.max(a.length(),b.length())+1;
        char[] res = new char[len];
        int i = a.length()-1;
        int j = b.length()-1;
        int k = res.length-1;
        int carry = 0;
        
        while(i>=0 && j>=0) {
            int sum = (a.charAt(i)-'0') + (b.charAt(j)-'0') + carry;
            if(sum > 1) {
                carry = 1;
                res[k] = (char)('0' + sum - 2);
            } else {
                carry = 0;
                res[k] = (char)('0'+sum);
            }
            i--;
            j--;
            k--;
        }
        
        while(i >= 0) {
            int sum = (a.charAt(i)-'0') + carry;
            if(sum > 1) {
                carry = 1;
                res[k] = (char)('0' + sum - 2);
            } else {
                carry = 0;
                res[k] = (char)('0'+sum);
            }
            i--;
            k--;
        }
        
        while(j >= 0) {
            int sum = (b.charAt(j)-'0') + carry;
            if(sum > 1) {
                carry = 1;
                res[k] = (char)('0' + sum - 2);
            } else {
                carry = 0;
                res[k] = (char)('0'+sum);
            }
            j--;
            k--;
        }
        
        if(carry > 0) {
            res[0] = '1';
            return new String(res);
        } else {
            return new String(res, 1, res.length-1);
        }
        
    }
}