给两个二进制字符串,返回它们的和(用二进制表示)。 输入为 非空 字符串且只包含数字 1 和 0。
示例 1: 输入: a = "11", b = "1" 输出: "100"
示例 2: 输入: a = "1010", b = "1011" 输出: "10101"
提示: 每个字符串仅由字符 '0' 或 '1' 组成。 1 <= a.length, b.length <= 10^4 字符串如果不是 "0" ,就都不含前导零。
package com.loo;
public class AddBinary { public static void main(String[] args) { System.out.println(addBinary2("1010" , "100011")); }
public static String addBinary(String a , String b) { if (a == null || b == null) { return ""; } if (a.length() == 0 || b.length() == 0) { return a+b; } int i = a.length() - 1; int j = b.length() - 1; int carry = 0; StringBuilder sb = new StringBuilder(); while (i>=0 || j>=0 || carry!=0) { carry += i>=0?a.charAt(i--)-'0':0; carry += j>=0?b.charAt(j--)-'0':0; sb.append(carry%2); carry = carry/2; } return sb.reverse().toString(); }
public static String addBinary2(String a , String b) { if (a == null || b == null) { return ""; } if (a.length() == 0 || b.length() == 0) { return a+b; } return addBinary22(a , a.length()-1 , b , b.length()-1 , 0); }
public static String addBinary22(String a , int i , String b , int j , int carry) { if (i<0 && j<0 && carry==0) { return ""; } carry += i<0?0:a.charAt(i--)-'0'; carry += j<0?0:b.charAt(j--)-'0'; int d = carry % 2; carry = carry / 2; String result = addBinary22(a , i , b , j , carry); return result + d; } }