标签:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:二进制基本运算规则
public static String addBinary(String a, String b) { if (null == a && null == b) { return null; } if (null == a) { return b; } if (null == b) { return a; } int carry = 0; int p1 = a.length() - 1; int p2 = b.length() - 1; StringBuilder result = new StringBuilder(); while (p1 >= 0 || p2 >= 0) { int sum = carry; if (p1 >= 0) { sum += (a.charAt(p1) - ‘0‘); } if (p2 >= 0) { sum += (b.charAt(p2) - ‘0‘); } char c = sum % 2 == 1 ? ‘1‘ : ‘0‘; result.insert(0, c); carry = sum / 2; p1--; p2--; } if (1 == carry) { result.insert(0, "1"); } return result.toString(); }
标签:
原文地址:http://www.cnblogs.com/zgcy123456/p/4300364.html