Leetcode 6667加法模拟题目

    技术2022-07-10  97

     

    注意只有最后一位正常加1,其他的遇到边界才+1

    class Solution { public: vector<int> plusOne(vector<int>& digits) { int i = digits.size() - 1, add = 0; while(i>=0){ int tmp; if(i==digits.size()-1) tmp = digits[i] + 1 + add; else tmp = digits[i] + add; add = tmp/10; tmp = tmp; digits[i] = tmp; if(add==0) break; i--; } if(add==1) digits.insert(digits.begin(), 1); return digits; } };

     

    class Solution { public: string addBinary(string a, string b) { string c; int i = a.size()-1, j = b.size()-1; int add = 0; while(i>=0||j>=0){ int tmp1=(i>=0?a[i]-'0':0); int tmp2=(j>=0?b[j]-'0':0); int tmp = tmp1+tmp2+add; add = tmp/2; tmp = tmp%2; c = to_string(tmp) + c; if(i>=0) i--; if(j>=0) j--; } if(add) c= "1" + c; return c; } };

     

    Processed: 0.012, SQL: 9