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.

Example:

If the vector has [1, 2, 3]

the returned vector should be [1, 2, 4]

as 123 + 1 = 124.

public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> a) {
int carry = 1;
int sum = 0;
int no = 0;
for(int i=a.size()-1; i>=0; i--){
sum = a.get(i) + carry;
no = sum%10;
carry = sum/10;
a.set(i,no);
if(carry == 0){
break;
}
}
if(carry != 0){
Collections.reverse(a);
a.add(carry);
Collections.reverse(a);
}else{
while (a.get(0) ==0 ){
a.remove(0);
}
}
return a;
}
}

All Posts
×

Almost done…

We just sent you an email. Please click the link in the email to confirm your subscription!

OKSubscriptions powered by Strikingly