Add Binary

lpy1990

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

思路

String的思路通常都是从后往前处理, 这道题重点是要考虑两个字符串长度不同的情况和char转换为number

复杂度

时间O(max(m,n)),空间O(max(m,n))

代码

public class Solution {

public String addBinary(String a, String b) {
    if (a == null || a.length() == 0) {
        return b;
    }
    if (b == null || b.length() == 0) {
        return a;
    }
    StringBuilder sb = new StringBuilder();
    int next = 0;
    int sum = 0;
    int i = a.length() -1;
    int j = b.length() -1;
    while (i >= 0 && j >= 0) {
        int inta = a.charAt(i) - '0';
        int intb = b.charAt(j) - '0';
        sum = inta + intb + next;
        next = sum/2;
        sb.append(sum%2);
        i--;
        j--;
    }
    while (i >= 0) {
        sum = a.charAt(i) - '0' + next;
        next = sum/2;
        sb.append(sum%2);
        i--;
    }
    while (j >= 0) {
        sum = b.charAt(j) - '0' + next;
        next = sum/2;
        sb.append(sum%2);
        j--;
    }
    if (next > 0) {
        sb.append(next);
    }
    return sb.reverse().toString();
}

}

阅读 926

26 声望
10 粉丝
0 条评论
26 声望
10 粉丝
文章目录
宣传栏