LeetCode_67---Add Binary

本文介绍了一种解决两个二进制字符串相加问题的方法,并提供了两种不同的Java实现方案。第一种方法使用数组来逐位处理进位,第二种方法则采用StringBuilder进行优化,提高了效率。

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

Hide Tags
  Math String
翻译:

Code:


/**
 * 
 */
package From61;

import java.util.Arrays;

/**
 * @author MohnSnow
 * @time 2015年6月29日 下午1:40:25
 * 
 */
public class LeetCode67 {

	/**
	 * @param argsmengdx
	 *            -fnst
	 */
	//360msAC----一次性提交通过
	public static String addBinary(String a, String b) {
		int a_len = a.length();
		int b_len = b.length();
		if (a_len == 0) {
			return b;
		} else if (b_len == 0) {
			return a;
		}
		int len = Math.max(a_len, b_len);
		int[] temp = new int[len];
		int tempInt = 0;
		for (int i = 1; i <= len; i++) {
			temp[len - i] = ((a_len - i) >= 0 ? a.charAt(a_len - i) - '0' : 0) + ((b_len - i) >= 0 ? b.charAt(b_len - i) - '0' : 0) + tempInt;
			System.out.println("temp[len - i]: " + temp[len - i]);
			if (temp[len - i] > 1) {
				tempInt = 1;
				temp[len - i] = temp[len - i] - 2;
			} else {
				tempInt = 0;
			}
		}
		StringBuffer result = new StringBuffer();
		if (tempInt == 1) {
			result.append("1");
		}
		for (int i = 0; i < len; i++) {
			result.append(temp[i]);
		}
		return result.toString();
	}

	//https://leetcode.com/discuss/35278/short-ac-solution-in-java-with-explanation
	//优化
	public String addBinary1(String a, String b) {
		StringBuilder sb = new StringBuilder();
		int i = a.length() - 1, j = b.length() - 1, carry = 0;
		while (i >= 0 || j >= 0) {
			int sum = carry;
			if (j >= 0)
				sum += b.charAt(j--) - '0';
			if (i >= 0)
				sum += a.charAt(i--) - '0';
			sb.append(sum % 2);
			carry = sum / 2;
		}
		if (carry != 0)
			sb.append(carry);
		return sb.reverse().toString();
	}

	public static void main(String[] args) {
		String a = "1";
		String b = "101";
		System.out.println("addBinary: " + addBinary(a, b));
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值