1. 程式人生 > >LeetCode 67 -Add Binary

LeetCode 67 -Add Binary

67. Add Binary

Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example 1: Input: a = "11", b = "1" Output: "100"Example 2: Input: a = "1010", b = "1011" Output: "10101"

給定兩個二進位制字串,返回他們的和(用二進位制表示)。

輸入為非空字串且只包含數字 1 和 0。

示例 1:

輸入: a = "11", b = "1" 輸出: "100" 示例 2:

輸入: a = "1010", b = "1011" 輸出: "10101"

【思路】

這道題,邏輯上十分簡單,比較麻煩的就是位數的判定和需要從後往前計算。將a長度和b長度中較大的那一個作為迴圈的次數,當取出字串中的值的時候,先判斷一下是否超過了字串長度,如果超出了直接用0計算,如果沒有超出取出其值。計算的時候需要記錄進位,當迴圈完之後,需要對進位進行判斷,如果進位不為0,需要把其加在最前面。

【程式碼】

class Solution {
	
    public String addBinary(String a, String b) {
    	
        int max_length = a.length() > b.length() ? a.length() : b.length();
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        
        for (int j = 1;j <= max_length; j++ )
        {
        	int a_value = a.length() >= j ? ((int)(a.charAt(a.length()-j))-(int)('0')) : 0;
        	int b_value = b.length() >= j ? ((int)(b.charAt(b.length()-j))-(int)('0')) : 0;
        	int value = a_value + b_value + carry;
        	if (value >= 2)  { 
        		value = value - 2;
        		carry = 1;
        		}
        	else 
        		carry = 0;
        	sb.append(value);
        }
        if (carry == 1)
        	sb.append(1);
        sb.reverse();
    	return sb.toString();
    }
}