• [LeetCode]二进制求和


    题目

     

    代码

    class Solution {
    public:
    	string addBinary(string a, string b)
    	{
    		int lenA = a.length();
    		int lenB = b.length();
    		string result;
    		int addFlag = 0;
    		int i;
    		int current = 0;
    		for (i = 0;i < lenA&&i < lenB;i++)
    		{
    			int numA = a[lenA - i - 1] - '0', numB = b[lenB - i - 1] - '0';
    			current = (addFlag + numA + numB) % 2;
    			result.push_back((char)('0' + current));
    			addFlag = numA + numB + addFlag > 1 ? 1 : 0;
    
    
    		}
    
    		if (lenA > lenB)
    		{
    			for (;i < lenA;i++)
    			{
    				current = ((a[lenA - i - 1] - '0') + addFlag) % 2;
    				result.push_back('0' + current);
    				addFlag = a[lenA - i - 1]-'0' + addFlag > 1 ? 1 : 0;
    			}
    			if (addFlag == 1)
    				result.push_back('1');
    		}
    		else if (lenA < lenB)
    		{
    			for (;i < lenB;i++)
    			{
    				current = ((b[lenB - i - 1] - '0') + addFlag) % 2;
    				result.push_back('0' + current);
    				addFlag = b[lenB - i - 1]-'0' + addFlag > 1 ? 1 : 0;
    			}
    			if (addFlag == 1)
    				result.push_back('1');
    		}
    		else
    		{
    			if (addFlag == 1)
    				result.push_back('1');
    		}
    		std::reverse(result.begin(), result.end());
    		return result;
    	}
    };
  • 相关阅读:
    django基础之ORM基础知识
    Centos7 搭建sonarQube
    centos7安装部署SVN
    centos7.5 SVN 搭建
    centos 7 部署 zookeeper
    centos7 发送邮件
    Centos7安装配置Gitlab-CE
    openldap 双主模式部署
    K8s一键安装
    ELK实战部署
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053579.html
Copyright © 2020-2023  润新知