题解 | #大数加法#
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
#include <string> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ string solve(string s, string t) { // write code here if(s.size() < t.size()) swap(s, t); // s为较长的字符串 int i = s.size()-1, j = t.size()-1; // 从末尾开始相加 int flag = 0; // 表示进位 string res = "" ; int temp = 0; while(j >=0 ){ int a = s[i] - '0'; int b = t[j] - '0'; temp = (a+b + flag) % 10; // 得到对应位上相加后的个位数结果 flag = (a + b + flag ) / 10; //是否进位 res += ('0' + temp); i--; j--; } while(i >= 0){ temp = ( s[i] - '0' ) + flag; flag = temp / 10; temp = temp % 10; res += ('0' + temp); i--; } if(flag == 1) res += '1'; //若最后留有进位补上 1 reverse(res.begin(), res.end()); //翻转字符串得到结果 return res; } };