-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAdd One To Number.java
More file actions
39 lines (26 loc) · 912 Bytes
/
Add One To Number.java
File metadata and controls
39 lines (26 loc) · 912 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
//https://www.interviewbit.com/problems/add-one-to-number/
public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
ArrayList<Integer> ans = new ArrayList<>();
boolean allZero = true;
for(int i = 0; i < A.size(); i++){
if(allZero && A.get(i) == 0)
continue;
allZero = false;
ans.add(ans.size(), A.get(i));
}
//get to the last index
int idx = ans.size() - 1;
int carry = 1;
while(idx >= 0){
int sum = carry + ans.get(idx);
carry = sum/10;
int num = sum%10;
ans.set(idx, num);
idx--;
}
if(carry != 0)
ans.add(0, carry);
return ans;
}
}