-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathadd_one_to_number.java
More file actions
44 lines (31 loc) · 930 Bytes
/
add_one_to_number.java
File metadata and controls
44 lines (31 loc) · 930 Bytes
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
/*
Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
*/
public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int size;
int carry = 1;
int num;
size = A.size();
for (int i = size - 1; i >= 0; i--) {
num = A.get(i);
num += carry;
carry = 0;
if (num == 10) {
num = 0;
carry = 1;
}
A.set(i, num);
}
ArrayList<Integer> res = new ArrayList<Integer>();
if (carry == 1)
res.add(1);
for (int x : A) {
if (x == 0 && res.size() == 0)
continue;
res.add(x);
}
return res;
}
}