zoukankan      html  css  js  c++  java
  • LeetCode-Add Two Binary

    Add BinaryApr 2 '12 3558 / 10570

    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) {
    		// Start typing your C/C++ solution below
    		// DO NOT write int main() function
    		string ret;
    		bool carry=false;
    		if(a.size()>b.size())
    		{
    			int i=a.size()-1,j=b.size()-1;
    			while(j>=0){
    				int sum=a.c_str()[i]+b.c_str()[j]-2*'0';
    				if(carry){
    					sum++;
    					carry=false;
    				}
    				if(sum>=2){
    					sum-=2;
    					carry=true;
    				}
    				char c=sum+'0';
    				ret=c+ret;
    				i--;
    				j--;
    			}
    			while(i>=0){
    				int sum=a.c_str()[i]-'0';
    				if(carry){
    					sum++;
    					carry=false;
    				}
    				if(sum>=2){
    					sum-=2;
    					carry=true;
    				}
    				char c=sum+'0';
    				ret=c+ret;
    				i--;
    			}
    		}
    		else
    		{
    			int i=a.size()-1,j=b.size()-1;
    			
    			while(i>=0){
    				int sum=a.c_str()[i]+b.c_str()[j]-2*'0';
    				if(carry){
    					sum++;
    					carry=false;
    				}
    				if(sum>=2){
    					sum-=2;
    					carry=true;
    				}
    				char c=sum+'0';
    				ret=c+ret;
    				i--;
    				j--;
    			}
    			while(j>=0){
    				int sum=b.c_str()[j]-'0';
    				if(carry){
    					sum++;
    					carry=false;
    				}
    				if(sum>=2){
    					sum-=2;
    					carry=true;
    				}
    				char c=sum+'0';
    				ret=c+ret;
    				j--;
    			}
    		}
    		if(carry)ret='1'+ret;
    		return ret;
    	}
    };
    

      

  • 相关阅读:
    572.Subtree of Another Tree
    35.Search Insert Position(二分查找)
    198.House Robber(dp)
    724.Find Pivot Index
    705.Design HashSet
    求连通分量(深搜)
    删边(normal)
    叠放箱子问题
    数字游戏
    火车票
  • 原文地址:https://www.cnblogs.com/superzrx/p/3179161.html
Copyright © 2011-2022 走看看