[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();
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83656193