- to do
1] Add Binary
表示数字时记住转换char<=>int
string addBinary(string a, string b) {
int carry = 0;
string ret = "";
for (auto i=a.rbegin(), j=b.rbegin(); i<a.rend() || j<b.rend(); ) {
int n1 = i<a.rend()? *i++ -'0' : 0;
int n2 = j<b.rend()? *j++ -'0' : 0;
int sum = n1 + n2 + carry;
ret.push_back(sum%2 + '0');
carry = sum>1? 1: 0;
}
if (carry) ret.push_back(carry+'0');
reverse(ret.begin(), ret.end());
return ret;
}
note the if statement for bound-checking. Although in c++11, a null terminator is guaranteed to guard anyways.
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
for (int i=0; i<strs[0].size(); ++i) {
for (int si=1; si<strs.size(); ++si) {
if (i>=strs[si].size() || strs[si][i]!=strs[0][i]) //note!
return strs[0].substr(0,i);
}
}
return strs[0];
}