Algorithms—67.Add Binary

原创 2015年07月09日 21:04:31

思路:按照二进制加法规则来。

public class Solution {
    public String addBinary(String a, String b) {
        if (a.equals("0")) {
			return b;
		}
    	if (b.equals("0")) {
			return a;
		}
    	if (a.length()<b.length()) {
			return new Solution().addBinary(b, a);
		}
    	int[] ia=new int[a.length()];
    	for (int i = a.length()-1; i >=0; i--) {
			ia[a.length()-1-i]=Integer.parseInt(a.substring(i, i+1));
		}
    	int[] ib=new int[b.length()];
    	for (int i = b.length()-1; i >=0; i--) {
			ib[b.length()-1-i]=Integer.parseInt(b.substring(i, i+1));
		}
    	int target=0;
    	int[] ias=new int[a.length()];
    	for (int i = 0; i < ia.length; i++) {
    		int k=0;
			if (i<ib.length) {
				k=ia[i]+ib[i]+target;
				ias[i]=k%2;
				target=k/2;
			}else {
				k=ia[i]+target;
				ias[i]=k%2;
				target=k/2;
			}
		}
    	StringBuffer sb=new StringBuffer();
    	if (target==1) {
			sb.append("1");
		}
    	for (int i = ias.length-1; i >=0 ; i--) {
			sb.append(""+ias[i]);
		}
    	return sb.toString();
    }
}


时间:336ms,中游水准。


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 67 — Add Binary(C++ Java Python)

题目:http://oj.leetcode.com/problems/add-binary/ Given two binary strings, return their sum (also a bi...

LeetCode(67) Add Binary

题目Given two binary strings, return their sum (also a binary string).For example, a = “11” b = “1” ...
  • fly_yr
  • fly_yr
  • 2015-08-19 20:58
  • 1614

67. Add Binary

Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1...

LeetCode 67 Add Binary(二进制相加)(*)

翻译给定两个二进制字符串,返回它们的和(也是二进制字符串)。例如, a = "11" b = "1" 返回 "100".原文Given two binary strings, return their...
  • NoMasp
  • NoMasp
  • 2016-02-02 13:49
  • 1837

LeetCode-67 Add Binary(二进制数相加)

LeetCode-67 Add Binary(二进制数相加) Given two binary strings, return their sum (also a binary string). ...

LeetCode笔记:67. Add Binary

模拟两个字符串二进制数的加法

Add Binary - LeetCode 67

题目描述:Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "...

【Leetcode】67. Add Binary

思路: (1)先求a、b长度的较大值len。 (2)在a和b中较短的字符串前面补齐0。 (3)用flag记录每一位的进位,result记录求和结果。 (4)从后往前遍历a和b,让相应位相加并加上fla...

LeetCode 67. Add Binary(二进制加)

原题网址:https://leetcode.com/problems/add-binary/ Given two binary strings, return their sum (also a ...

LeetCode-67. Add Binary

问题描述Given two binary strings, return their sum (also a binary string). For example, a = “11” b = ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)