LeetCode|AddBinary

2014-11-24 11:48:49 · 作者: · 浏览: 1

题目

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

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


思路

恩..其实这道题可以简单点的,用BigInteger来做..比较恶心..

但是还是乖点,用标准的做法吧

分析:

2个二进制相加,最多是进1!而且最大是数字是3 比如 11+11 = 100 最多就进1,而且最多就是3(1+1+1).

所以,写一个函数用来计算某2个字符相加的结果,用一个私有属性保存溢出数字(lastFlow).

好了。通过3个while来做。最后如果lastFlow不为0,那么就要在给值.

好了.ok..

这道题其实困住我了...巩固了

代码

public class Solution {
	private int lastFlow = 0;
	
	private int add(char a,char b)
	{
		int result = a+b+lastFlow-48*2;
		
		if( result > 1)
		{
			lastFlow = 1;
			return result%2;
		}
		else
		{
			lastFlow = 0;
			return result;
		}
	}
	
	public String addBinary(String a, String b)
	{
		String result ="";		
		
		int lengthOfA = a.length() - 1;
		int lengthOfB = b.length() -1;
		
		while(lengthOfA >=0 && lengthOfB >=0)
		{
			int temp  = add(a.charAt(lengthOfA),b.charAt(lengthOfB));
			result+=temp+"";
			lengthOfA--;
			lengthOfB--;
		}
		
		while(lengthOfA >=0 )
		{			
			int temp = a.charAt(lengthOfA)-48+lastFlow;
			if( temp >1)
			{
				lastFlow = 1;
				temp = temp%2;
			}
			else
			{
				lastFlow =0;
			}
			result +=temp+"";
			lengthOfA--;
		}
		
		while(lengthOfB >=0 )
		{
			int temp = b.charAt(lengthOfB)-48+lastFlow;
			if( temp >1)
			{
				lastFlow = 1;
				temp = temp%2;
			}
			else
			{
				lastFlow =0;
			}
			result +=temp+"";
			lengthOfB--;
		}
		
		if( lastFlow > 0)
		{
			result+=lastFlow+"";
		}
	 	 
		StringBuffer sb=new StringBuffer(result);
		sb=sb.reverse();
		return sb.toString();
	}
}