首页 > 其他 > 详细

989. Add to Array-Form of Integer

时间:2020-06-02 16:35:54      阅读:29      评论:0      收藏:0      [点我收藏+]

问题:

给定一个数组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 };

 

989. Add to Array-Form of Integer

原文:https://www.cnblogs.com/habibah-chang/p/13031317.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!