1. 程式人生 > >[LeetCode] 67. Add Binary

[LeetCode] 67. Add Binary

題:https://leetcode.com/problems/add-binary/description/

題目

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"

題目大意

二進位制 字串 加法

思路

設定 兩指標 i,j 指向 字串a、b的尾部。設定 count 為本位的進位(該值由上位計算出)。

若 指標 i 大於等於0,這count += a[i] - ‘0’;
若 指標 j 大於等於0,這count += a[j] - ‘0’;

res += count%2,計算結果中 本位的值
count = count/2,計算下一位的進位。

class Solution {
    public String addBinary(String a, String b) {
        int i = a.length()-1,j =
b.length()-1; StringBuilder res = new StringBuilder(); int count = 0; while(i>=0 || j>=0 || count>0){ if(i>=0 && a.charAt(i--)=='1') count +=1; if(j>=0 && b.charAt(j--)=='1') count +=1; res.
append(count%2); count =count / 2; } return res.reverse().toString(); } }