【Java】Given two binary strings, return their sum

来源:互联网 发布:怎么彻底删除手机数据 编辑:程序博客网 时间:2024/06/05 20:37
/** * Given two binary strings, return their sum (also a binary string). *  * For example, a = "11" b = "1" Return "100". *  * 2014年10月27日 18:55:23 */public class AddBinary {public static void main(String[] args) {System.out.println(addBinary("1111", "1"));}public static String addBinary(String a, String b) {/** a的长度 */int i = a.length() - 1;/** b的长度 */int j = b.length() - 1;/** a中的字符 */int da = 0;/** b中的字符 */int db = 0;/** 进位 0或1 */int adv = 0;/** * StringBuffer的内部实现方式和String不同,所以StringBuffer在进行字符串处理时,不生成新的对象, * 在内存使用上要优于String类。 * 所以在实际使用时,如果经常需要对一个字符串进行修改,例如插入、删除等操作,使用StringBuffer要更加适合一些。 */StringBuffer result = new StringBuffer();/** 相似部分相加的二进制 */while (i >= 0 && j >= 0) {da = a.charAt(i--) == '0' ? 0 : 1;db = b.charAt(j--) == '0' ? 0 : 1;int d = da + db + adv;result.append(d % 2 == 0 ? '0' : '1');/** 运算符优先级 :带符号右移位运算符优先级高于等于号 */adv = d >> 1;// 进位}if (i >= 0) {// 字符串a比较长while (i >= 0) {da = a.charAt(i--) == '0' ? 0 : 1;int d = da + adv;result.append(d % 2 == 0 ? '0' : '1');adv = d >> 1;}} else if (j >= 0) {// 字符串b比较长while (j >= 0) {db = b.charAt(j--) == '0' ? 0 : 1;int d = db + adv;result.append(d % 2 == 0 ? '0' : '1');adv = d >> 1;}}if (adv == 1) {result.append('1');}/** 反转 */return result.reverse().toString();}}

0 0