关闭

LeetCode-Add Binary-解题报告

标签: C++leetcodestring
123人阅读 评论(0) 收藏 举报
分类:

原题链接 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;
	}
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14593次
    • 积分:844
    • 等级:
    • 排名:千里之外
    • 原创:72篇
    • 转载:6篇
    • 译文:0篇
    • 评论:0条
    文章分类