zoukankan      html  css  js  c++  java
  • leetcode--Add Binary

    Given two binary strings, return their sum (also a binary string).

    For example,
    a = "11"
    b = "1"
    Return "100".

    Have you been asked this question in an interview? 

    Discuss


    class Solution {
    public:
        string addBinary(string a, string b) 
        {
            int lena = a.size();
            int lenb = b.size();
            int i,j;
            if(lena==0||lenb==0)return a+b;
            string str;
            int carry = 0;
            int tem;
            for(i=lena-1, j=lenb-1;i>=0&&j>=0;i--,j--)
            {
                tem   = (a[i]+b[j]+carry-2*'0')%2;
                carry = (a[i]+b[j]+carry-2*'0')/2;
                str = (char)(tem + '0') + str;
                
            }
            if(i>=0)
            {
                while(i!=-1)
                {  
                   
                    tem   = (a[i]+carry-'0')%2;
                    carry = (a[i]+carry-'0')/2;
                    str = (char)(tem + '0') + str;
                     i--;
                }
            }
            if(j>=0)
            {
                while(j!=-1)
                {
                   
                tem   = (b[j]+carry-'0')%2;
                carry = (b[j]+carry-'0')/2;
                str = (char)(tem + '0') + str;
                 j--;
                }
            }
            if(carry==1)
                str = '1'+str;
            return str;
        }
    };


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    jvm09
    jvm08
    jvm07
    求解最长公共子序列问题
    归并排序
    求解N皇后问题
    快速排序算法
    求解0/1背包问题
    求解全排列问题
    求解最大连续子序列和问题
  • 原文地址:https://www.cnblogs.com/vintion/p/4116902.html
Copyright © 2011-2022 走看看