题解 | #大数加法#
大数加法
http://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
这个题和链表和是一致的
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ string solve(string s, string t) { // write code here stack<int> left_string; stack<int> right_string; stack<int> result; string res = ""; int max_length = 0; for(int i = 0; i< s.length();i++){ left_string.push(s[i]-'0'); } for(int i = 0; i< t.length();i++){ right_string.push(t[i]-'0'); } if(left_string.size()>=right_string.size()){ max_length = left_string.size(); }else{ max_length = right_string.size(); } int add_on = 0; while(max_length){ int up = 0; int down = 0; if(!left_string.size()){ up = 0; }else{ up = left_string.top(); left_string.pop(); } if(!right_string.size()){ down = 0; }else{ down = right_string.top(); right_string.pop(); } int sum = up+down + add_on; add_on = 0; if(sum>=10){ result.push(sum-10) ; add_on = 1; if(max_length==1){ result.push(1); } }else{ result.push(sum); } max_length--; } while(!result.empty()){ res+= result.top() + '0'; result.pop(); } return res; } };
算法解析 文章被收录于专栏
这里主要是算法岗的自我思路总结