leetcode-华为专题-989. 数组形式的整数加法
class Solution { public: vector<int> addToArrayForm(vector<int>& num, int k) { vector<int> vec; string str_k = to_string(k); // cout<<"num: "<<num.size()<<" "<<str_k.length()<<endl; vector<int> res; int i = str_k.size()-1; int j = num.size()-1; int sum = 0; int cur = 0; int high = 0; int temp = 0; while((j>=0||i>=0)){ if(i>=0&&j>=0){ // 两个一样长 temp = num[j]+(str_k[i]-'0'); }else if(j>=0&&i<0){ // 一长一短 temp = num[j]; }else if(i>=0&&j<0){ temp = str_k[i]-'0'; } cur = (temp+high)%10; // 当前为等于(两数当前位之和+上次的进位)%10 high = (temp+high)/10; // 进位等于(两数当前位之和+上次的进位)/10 // sum = sum * 10 + cur; res.push_back(cur); j--; i--; } if(high>0) // 如果最高位存在进位,加上 res.push_back(high); for(int i = 0; i < res.size(); i++){ cout<<i<<" : "<<res[i]<<endl; } reverse(res.begin(), res.end()); // 反转 return res; } };