[LeetCode] Add Binary

来源:互联网 发布:淘宝宝贝排名靠前 编辑:程序博客网 时间:2024/06/06 08:30
Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"

Return "100".


public class Solution {    public String addBinary(String a, String b) {        if (a == null || a.length() < 1) {            return b;        }                if (b == null || b.length() < 1) {            return a;        }                int aLen = a.length();        int bLen = b.length();        int maxLen = aLen > bLen ? aLen : bLen;                String res = "";        char carry = '0';        for (int i = 0; i < maxLen; i++) {            int num1 = 0;            if (carry == '1') {                num1++;            }            if (i < aLen && a.charAt(aLen - i - 1) == '1') {                num1++;            }            if (i < bLen && b.charAt(bLen - i - 1) == '1') {                num1++;            }                         switch (num1) {                case 0 :                    carry = '0';                    res = "0" + res;                    break;                case 1 :                    carry = '0';                    res = "1" + res;                    break;                case 2 :                    carry = '1';                    res = "0" + res;                    break;                case 3 :                    carry = '1';                    res = "1" + res;                    break;            }        }                if (carry == '1') {            res = "1" + res;        }                return res;    }}


0 0
原创粉丝点击