[leetcode]67. Add Binary 二进制加法

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"

注意:

StringBuilder.insert(int offset,  char c) 表示将char放入offset这个偏移量

Character.forDigit(int digit, int radix) 返回radix进制下,该digit所代表的char

代码

 class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder(); // new a StringBuilder because it will be easy to append char[] arrayA = a.toCharArray();// convert char to array
char[] arrayB = b.toCharArray();// convert char to array int i = a.length()-1;
int j = b.length()-1;
int carry = 0; while(i>=0 || j>=0 || carry >0){
int updateA = i>=0 ? arrayA[i--]-'0':0;
int updateB = j>=0 ? arrayB[j--]-'0':0;
int sum = updateA + updateB + carry;
sb.insert(0, Character.forDigit(sum%2, 10)); // I convert this sum to binary then insert to sb
carry = sum/2; // coz it is binary, carry would be sum/2
}
return sb.toString(); // convert StringBuilder to String
}
}
上一篇:dubbo在项目中的应用


下一篇:JQuery & Javascript