leetcode415 大数相加
string addStrings(string num1, string num2) { int n = num1.size(), m = num2.size(); // 补齐 if(n < m) for(int i = n;i < m;i++) num1 = '0' + num1; else for(int i = m;i < n;i++) num2 = '0' + num2; cout << num1 << " " << num2 << endl; int carry = 0; string res = ""; for(int i = max(n,m)-1;i >= 0;i--) { int tmp = (num1[i]-'0') + (num2[i]-'0') + carry; res = to_string(tmp%10) + res; carry = tmp/10; } if(carry != 0) res = to_string(carry) + res; return res; }
注:to_string(int a)-->string,如果参数是char,会转成assic码。
例如,to_string(9) --> "9",to_string('9')--> "57"
个性签名:时间会解决一切