N是进制,二进制N = 2, 十进制N = 10
import java.util.*; public class Solution { /** * * @param a string字符串 * @param b string字符串 * @return string字符串 */ private static final int N = 2; 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 carry = 0; int i1 = a.length() - 1; int i2 = b.length() - 1; while (i1 >= 0 || i2 >= 0) { int n1 = i1 >= 0 ? a.charAt(i1--) - '0' : 0; int n2 = i2 >= 0 ? b.charAt(i2--) - '0' : 0; int sum = carry + n1 + n2; carry = sum / N; sum %= N; sb.append(sum); } if (carry > 0) { sb.append(carry); } return sb.reverse().toString(); } }