6.26 ->30 addBinary & longestCommonPrefix

  • to do

6.26 ->30 addBinary & longestCommonPrefix_第1张图片

1] Add Binary
表示数字时记住转换char<=>int

    string addBinary(string a, string b) {
        int carry = 0;
        string ret = "";
        for (auto i=a.rbegin(), j=b.rbegin(); i1? 1: 0;
        }
        if (carry) ret.push_back(carry+'0');
        reverse(ret.begin(), ret.end());
        return ret;
    }

5] Longest Common Prefix

note the if statement for bound-checking. Although in c++11, a null terminator is guaranteed to guard anyways.

    string longestCommonPrefix(vector& strs) {
        if (strs.empty()) return "";
        for (int i=0; i=strs[si].size() || strs[si][i]!=strs[0][i]) //note!
                    return strs[0].substr(0,i);
            }
        }
        return strs[0];
    }

你可能感兴趣的:(6.26 ->30 addBinary & longestCommonPrefix)