码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 64 add binary

时间:2020-07-10 20:58:33      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:mamicode   dbi   public   info   str   i++   mic   长度   tco   

题目

Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or?0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
Each string consists only of ‘0‘ or ‘1‘ characters.
1 <= a.length, b.length <= 10^4
Each string is either "0" or doesn‘t contain any leading zero.

思路

技术图片

代码

Code 01

class Solution {
public:
    string addBinary(string a, string b) {
        reverse(a.begin(),a.end()); //从低位开始处理
        reverse(b.begin(),b.end());
        string c;
        int r = 0; 
        int len = max(a.length(),b.length()); //取较大字符串长度
        for(int i=0;i<len;i++){
            r+=i<a.length()?a.at(i)==‘1‘:0; //累加a中第i位的数字
            r+=i<b.length()?b.at(i)==‘1‘:0; //累加b中第i位的数字
            c.push_back(r%2?‘1‘:‘0‘); // 记录当前和数字
            r/=2; //更新当前余数
        }
        if(r!=0)c.push_back(‘1‘); //处理最高位进位
        reverse(c.begin(),c.end()); //存储为低位到高位,反转后为高位到低位
        return c;
    }
};

leetcode 64 add binary

标签:mamicode   dbi   public   info   str   i++   mic   长度   tco   

原文地址:https://www.cnblogs.com/houzm/p/13281095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!