-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path66. Plus One.c
65 lines (53 loc) · 1.52 KB
/
66. Plus One.c
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
54
55
56
57
58
59
60
61
62
63
64
65
/*
66. Plus One
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize) {
int s = 1;
int i;
int *p;
p = malloc((digitsSize + 1) * sizeof(int));
if (!p) return NULL;
i = digitsSize - 1;
while (i >= 0) {
//if (s) {
p[i] = (digits[i] + s) % 10;
s = (digits[i] + s) / 10;
//} else {
// p[i] = digits[i];
//}
i --;
}
if (s) {
memcpy(&p[1], &p[0], digitsSize * sizeof(int));
//i = digitsSize - 1;
//while (i >= 0) {
// p[i + 1] = p[i];
// i --;
//}
p[0] = 1;
*returnSize = digitsSize + 1;
} else {
*returnSize = digitsSize;
}
return p;
}
/*
Difficulty:Easy
Total Accepted:181.2K
Total Submissions:469.5K
Companies Google
Related Topics Array Math
Similar Questions
Multiply Strings
Add Binary
Plus One Linked List
*/