首页 > 其他 > 详细

LeetCode | Add Binary

时间:2014-03-16 01:17:17      阅读:468      评论:0      收藏:0      [点我收藏+]

题目

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

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

分析

本想图省事,直接用java类库里提供的parseLong函数,结果测试用例里面会给出很长的字符串。

那就只能按规矩写了。

代码

public class AddBinary {
	public static final int RADIX = 2;

	public String addBinary(String a, String b) {
		int shorterLen = a.length();
		int longerLen = b.length();
		char[] shorterArray = a.toCharArray();
		char[] longerArray = b.toCharArray();
		if (a.length() > b.length()) {
			shorterLen = b.length();
			longerLen = a.length();
			// swap
			char[] temp = shorterArray;
			shorterArray = longerArray;
			longerArray = temp;
		}
		int carry = 0;
		for (int i = 0; i < shorterLen; ++i) {
			int result = (shorterArray[shorterLen - 1 - i] - ‘0‘)
					+ (longerArray[longerLen - 1 - i] - ‘0‘) + carry;
			carry = result / RADIX;
			longerArray[longerLen - 1 - i] = (char) (result % RADIX + ‘0‘);
		}
		for (int i = longerLen - shorterLen - 1; i >= 0; --i) {
			int result = (longerArray[i] - ‘0‘) + carry;
			carry = result / RADIX;
			longerArray[i] = (char) (result % RADIX + ‘0‘);
		}

		String result = new String(longerArray);
		if (carry == 1) {
			result = 1 + result;
		}
		return result;
	}
}

LeetCode | Add Binary,布布扣,bubuko.com

LeetCode | Add Binary

原文:http://blog.csdn.net/perfect8886/article/details/21275951

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!