LeetCode-Add Binary-解题报告

原创 2015年07月08日 21:00:37

原题链接 https://leetcode.com/problems/add-binary/

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

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

很简单和做大数加法一样的做法


class Solution {
public:
    string addBinary(string a, string b) {
		int al = a.length();
		int bl = b.length();
		if (al > bl)for (int i = 0; i < al - bl; ++i)b = '0' + b;
		if (bl > al)for (int i = 0; i < bl - al; ++i)a = '0' + a;
		int l = max(al, bl);
		int c = 0;
		string ans = "";
		for (int i = l - 1; i >= 0; --i)
		{
			int op1 = a[i] - '0';
			int op2 = b[i] - '0';
			ans = string(1, (op1 + op2 + c) % 2 + '0') + ans;
			c = (op1 + op2 + c) / 2;
		}
		if (c)ans = "1" + ans;
		return ans;
	}
};


Add Binary | leetcode 67 【Java解题报告】

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

[leetcode] 211. Add and Search Word - Data structure design 解题报告

题目链接: https://leetcode.com/problems/add-and-search-word-data-structure-design/ Design a data struc...

LeetCode 415. Add String 解题报告

LeetCode 415. Add String 解题报告

【LeetCode】 Add Digits 解题报告

Add Digits [LeetCode] Given a non-negative integer num, repeatedly add all its digits until the resu...

leetcode解题报告2. Add Two Numbers

leetcode解题报告2. Add Two Numbers题目地址 难度是medium题目描述用单链表来表示一个大整数,其中单链表的每个节点只有一个数0~9。给两个这样单链表表示的整数,求它们的和(...

[LeetCode]Add and Search Word - Data structure design,解题报告

目录目录 思路 思路 AC代码思路Design a data structure that supports the following two operations: void addWord(...

[LeetCode] Add Two Numbers 解题报告

—— write for my baby, mua [题目] You are given two linked lists representing two non-negative numb...

【LeetCode】2. Add Two Numbers 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51820937Subject 出处:https://leetcode.com/pro...

LeetCode 2. Add Two Numbers 解题报告

题意: 有两个链表,它们表示逆序的两个非负数。例 (2 -> 4 -> 3)表示342,求两个数字的和,并用同样的方式逆序输出。如342+465 = 807,你需要把结果表达为(7 ->0 ->8)...

[leetcode] 96. Unique Binary Search Trees 解题报告

题目链接:https://leetcode.com/problems/unique-binary-search-trees/ Given n, how many structurally uniq...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode-Add Binary-解题报告
举报原因:
原因补充:

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