模拟大数相加

    注意最后要判断进位

    1. class Solution {
    2. public:
    3. string addStrings(string num1, string num2) {
    4. string res = "";
    5. int i = num1.length()-1, j = num2.length()-1;
    6. int cnt = 0;
    7. while(i >=0 || j >= 0){
    8. if(i >= 0 && j >= 0){
    9. int a = num1[i]-'0', b = num2[j]-'0';
    10. res += (a + b + cnt)%10 + '0';
    11. cnt = (a + b + cnt)/10;
    12. i--;
    13. j--;
    14. }else if(i >= 0){
    15. int x = num1[i] - '0';
    16. res += (x + cnt)%10 + '0';
    17. cnt = (cnt + x)/10;
    18. i--;
    19. }else if(j >= 0){
    20. int y = num2[j]-'0';
    21. res += (y + cnt)%10 + '0';
    22. cnt = (cnt + y)/10;
    23. j--;
    24. }
    25. }
    26. if(cnt > 0) res += cnt+'0';
    27. reverse(res.begin(), res.end());
    28. return res;
    29. }
    30. };