989. Add to Array-Form of Integer
问题:
给定一个数组A为某个数的各位数,和数字K,求给A组成的数字+K,所得的数字也像A做成数组返回。
Example 1: Input: A = [1,2,0,0], K = 34 Output: [1,2,3,4] Explanation: 1200 + 34 = 1234 Example 2: Input: A = [2,7,4], K = 181 Output: [4,5,5] Explanation: 274 + 181 = 455 Example 3: Input: A = [2,1,5], K = 806 Output: [1,0,2,1] Explanation: 215 + 806 = 1021 Example 4: Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1 Output: [1,0,0,0,0,0,0,0,0,0,0] Explanation: 9999999999 + 1 = 10000000000 Note: 1 <= A.length <= 10000 0 <= A[i] <= 9 0 <= K <= 10000 If A.length > 1, then A[0] != 0 |
解法:
从个位往十位,百位,千位,
每次求K的各位数值:K%10,直接加给A[j]
预留下的K/10,为下一位计算原数。
对于加得之和,用flag记录进位,如果有进位,直接加给K。
即K=K/10+flag
A[j]则只保留个位,
即A[j]=A[j]%10
⚠️注意,
这里如果A的位数不够,
判断 j<0 的时候
需要insert(0)到A的开头A.begin()
同时把要处理的 j 置为 0。
代码参考:
1 class Solution { 2 public: 3 vector<int> addToArrayForm(vector<int>& A, int K) { 4 int flag=0; 5 int j=A.size()-1; 6 while(K>0){ 7 if(j<0){ 8 A.insert(A.begin(),0); 9 j=0; 10 } 11 A[j]+=K%10; 12 flag=A[j]/10; 13 A[j]=A[j]%10; 14 K=K/10+flag; 15 j--; 16 } 17 return A; 18 } 19 };