https://leetcode.com/problems/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) { string c="",d=""; if(a=="0"&&b=="0") return "0"; int a_t=a.size(),b_t=b.size(),min_t=min(a_t,b_t),max_t=max(a_t,b_t); int tmp_a,tmp_b,jinyi=0; for(int i=0;i<max_t;i++){ if(i<a_t) tmp_a=a[a_t-i-1]-‘0‘; else tmp_a=0; if(i<b_t) tmp_b=b[b_t-i-1]-‘0‘; else tmp_b=0; c.push_back((tmp_a+tmp_b+jinyi)%2+‘0‘); if(tmp_a+tmp_b+jinyi>=2) jinyi=1; else jinyi=0; } if(jinyi==1) c.push_back(‘1‘); for(int i=c.size()-1;i>=0;i--) d.push_back(c[i]); return d; } };
时间: 2024-11-29 04:07:29