Add Binary

来源:互联网 发布:用windows7引导ubuntu 编辑:程序博客网 时间:2024/06/07 09:26

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

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

Show Tags
思路: Using stringBuilder to reverse these two strings,then add them to the end of the short one. Add the rest of the longer one. At last, reverse the result and create a new String by this result.
易错点:1. carry 应该直接加在 cur上。 2. i 第一次只加到两个string 的较短的结尾,千万别忘记把剩余的长的也加上。 3. 最后剩余一个carry 小尾巴有可能为1.

public class Solution {    public String addBinary(String a, String b) {        StringBuilder sb1 = new StringBuilder(a);        StringBuilder sb2 = new StringBuilder(b);        sb1 = sb1.reverse();        sb2 = sb2.reverse();        StringBuilder ret = new StringBuilder();        int i = 0;        int carry = 0;        while(i < sb1.length() && i < sb2.length()){            int cur = sb1.charAt(i) - '0' + sb2.charAt(i) - '0' + carry;            ret.append(cur % 2);            carry = cur / 2;            i++;        }        sb1 = (sb1.length() > sb2.length()) ? sb1 : sb2;        while(i < sb1.length()){            int cur = sb1.charAt(i) - '0' + carry;            ret.append(cur % 2);            carry = cur / 2;            i++;        }        if(carry > 0){            ret.append(1);        }        return new String(ret.reverse());    }}


0 0