LeetCode 67. 二进制求和
发布日期:2021-07-01 03:15:38 浏览次数:2 分类:技术文章

本文共 1935 字,大约阅读时间需要 6 分钟。

1. 题目

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0。

示例 1:输入: a = "11", b = "1"输出: "100"示例 2:输入: a = "1010", b = "1011"输出: "10101"

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/add-binary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 用一个变量存储进位(直白解法,代码有点长)
    在这里插入图片描述
class Solution {
public: string addBinary(string a, string b) {
int i, j, one = 0; string ans; for(i = a.size()-1,j = b.size()-1; i >= 0 && j >= 0; --i,--j) {
if((a[i]-'0')^(b[j]-'0')) {
if(one == 0) ans = "1"+ans; else ans = "0"+ans; } else {
if(a[i]== '0' && b[j]== '0') {
if(one == 0) ans = "0"+ans; else {
ans = "1"+ans; one = 0; } } else//都为1 {
if(one == 0) {
ans = "0"+ans; one = 1; } else ans = "1"+ans; } } } if(j < 0 && i >= 0) {
while(i >= 0) {
if((a[i]-'0')^one) {
ans = "1"+ans; one = 0; } else {
if(a[i]== '0' && one == 0) ans = "0"+ans; else {
ans = "0"+ans; one = 1; } } i--; } if(one) ans = "1"+ans; } else // (i < 0) {
while(j >= 0) {
if((b[j]-'0')^one) {
ans = "1"+ans; one = 0; } else {
if(b[j]== '0' && one == 0) ans = "0"+ans; else {
ans = "0"+ans; one = 1; } } j--; } if(one) ans = "1"+ans; } return ans; }};

转载地址:https://michael.blog.csdn.net/article/details/101211346 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 1046. 最后一块石头的重量(priority_queue 堆)
下一篇:LeetCode 1009. 十进制整数的反码(位运算)

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月13日 08时23分33秒