题解 | #大数加法#
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
//c++ #include <algorithm> #include <iostream> #include <iterator> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ string solve(string s, string t) { // write code here int len1=s.size(); int len2=t.size(); // 首先要保证两个数的位数要保持一致 while(len1<len2){ s="0"+s; len1++; } while(len1>len2){ t="0"+t; len2++; } string ans; int carry=0; // 定义一个变量作为进位位 for(int i=len1-1;i>=0;i--){ //char变为int,那就要-’0‘ int tmp=(s[i]-'0'+t[i]-'0'+carry);\ //整形自动转为char形,+'0' ans+=char(tmp%10+'0'); carry=tmp/10; // 不断更新进位位 } // 最后还需要特判进位位 if(carry){ ans+=char(carry+'0'); } // cout << "ans : " << ans<< endl; reverse(ans.begin(),ans.end()); return ans; } };