leetcode-67-easy

Add Binary
思路一: 先计算公共部分,最后补充未计算的位置,模拟二进制加法,写的太丑了

public String addBinary(String a, String b) {
    char ONE = '0' + '1';
    char TWO = '1' + '1';

    StringBuilder sb = new StringBuilder();
    int as = a.length() - 1;
    int bs = b.length() - 1;
    char x = '0';
    while (as >= 0 && bs >= 0) {
        if (a.charAt(as) + b.charAt(bs) == TWO) {
            sb.insert(0, x);
            x = '1';
        } else if (a.charAt(as) + b.charAt(bs) == ONE) {
            if (x == '1') {
                sb.insert(0, '0');
                x = '1';
            } else {
                sb.insert(0, '1');
            }
        } else {
            sb.insert(0, x == '1' ? '1' : '0');
            x = '0';
        }

        as--;
        bs--;
    }

    while (as >= 0) {
        if (a.charAt(as) + x == TWO) {
            sb.insert(0, '0');
            x = '1';
        } else  if (a.charAt(as) + x == ONE){
            sb.insert(0, '1');
            x = '0';
        } else {
            sb.insert(0, '0');
        }
        as--;
    }
    while (bs >= 0) {
        if (b.charAt(bs) + x == TWO) {
            sb.insert(0, '0');
            x = '1';
        } else if (b.charAt(bs) + x == ONE) {
            sb.insert(0, '1');
             x = '0';
        } else {
            sb.insert(0, '0');
        }
        bs--;
    }
    if (x == '1') sb.insert(0, '1');

    return sb.toString();
}
posted @ 2022-10-11 22:13  iyiluo  阅读(24)  评论(0)    收藏  举报