程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode] Add Binary

[LeetCode] Add Binary

編輯:C++入門知識

[LeetCode] Add Binary


 

Add Binary

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) {
        int len1=a.length();
        int len2=b.length();
        int carry=0;
        string result="";
        int i=len1-1, j=len2-1;
        while(i>=0&&j>=0){
            int r = (a[i]-'0') + (b[j]-'0') + carry;
            result =  (r%2==0 ? "0": "1") + result;
            carry = r/2;
            i--;
            j--;
        }
        while(i>=0){
            int r = (a[i]-'0') + carry;
            result = (r%2==0 ? "0": "1") + result;
            carry = r/2;
            i--;
        }
        while(j>=0){
            int r = (b[j]-'0') + carry;
            result = (r%2==0 ? "0": "1") + result;
            carry = r/2;
            j--;
        }
        if(carry>0){
            result = "1" + result;
        }
        return result;
    }
};


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved