码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Add Binary

时间:2015-02-25 23:34:36      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

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();
	}

  

 

[LeetCode] Add Binary

标签:

原文地址:http://www.cnblogs.com/zgcy123456/p/4300364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!