标签:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
class Solution { public: char intToChar(int input){ char strBuffer[1] = {0}; sprintf(strBuffer, "%d", input); return strBuffer[0]; } string addB(string a, string b){ string result; for(int i = a.size() - 1; i >=0 ; --i){ int aDigital = a[i] - ‘0‘; int bDigital = b[i] - ‘0‘; int sumResult = aDigital + bDigital; if(sumResult >= 2){ if(sumResult == 2){ result.push_back(‘0‘); }else{ result.push_back(‘1‘); } if(i - 1 >= 0){ a[i - 1] = intToChar(a[i - 1] - ‘0‘ + 1); }else{ result.push_back(‘1‘); } }else{ result.push_back(intToChar(sumResult)); } } reverse(result.begin(), result.end()); return result; } string addBinary(string a, string b) { size_t sizeA = a.size(); size_t sizeB = b.size(); // 不等则对齐 if (sizeA > sizeB) { b.insert(b.begin(), sizeA-sizeB, ‘0‘); } else if (sizeA < sizeB) { a.insert(a.begin(), sizeB-sizeA, ‘0‘); } return addB(a, b); } };
1.这里使用些技巧,首先是把短的字符串前面补0,用到了insert方法。然后就是按照人工的相加方法,从最后一位开始加,如果大于等于2就把前一位的数字加1.最后的结果要逆序下。如果知道一个char是一个数字,比如想把‘9’ 转成 int的9,可以把‘9’ - ‘0’即可。
http://www.waitingfy.com/archives/1686
标签:
原文地址:http://blog.csdn.net/fox64194167/article/details/45440271