-
Notifications
You must be signed in to change notification settings - Fork 115
/
0989-AddToArrayFormOfInteger.cs
53 lines (45 loc) · 1.33 KB
/
0989-AddToArrayFormOfInteger.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//-----------------------------------------------------------------------------
// Runtime: 284ms
// Memory Usage: 38.8 MB
// Link: https://leetcode.com/submissions/detail/352428880/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0989_AddToArrayFormOfInteger
{
public IList<int> AddToArrayForm(int[] A, int K)
{
var result = new List<int>();
var carry = 0;
var i = A.Length - 1;
while (i >= 0 && K > 0)
{
var sum = A[i--] + K % 10 + carry;
K /= 10;
var digit = sum % 10;
carry = sum / 10;
result.Add(digit);
}
while (i >= 0)
{
var sum = A[i--] + carry;
var digit = sum % 10;
carry = sum / 10;
result.Add(digit);
}
while (K > 0)
{
var sum = K % 10 + carry;
K /= 10;
var digit = sum % 10;
carry = sum / 10;
result.Add(digit);
}
if (carry > 0)
result.Add(carry);
result.Reverse();
return result;
}
}
}