• 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;
    	}
    };
    

      

  • 相关阅读:
    火车进出栈问题(卡特兰数)
    HDU 4699 Editor (对顶栈)
    HDU 6430 TeaTree (线段树合并)
    Exam 4895 Crowd Control
    Exam 4894 Booming Business
    8377: Playoff
    hdu 6345 Problem J. CSGO
    HDU 6437 Problem L.Videos
    Making the Grade
    poj2279——Mr. Young's Picture Permutations
  • 原文地址:https://www.cnblogs.com/superzrx/p/3179161.html
Copyright © 2020-2023  润新知