This is a asked question: Given a non-negative number represented as an array of numbers,
add 1 to the number (increase the number indicated by numbers).
The numbers are stored so that the most significant digit is at the head of the list.
Example:
If the vector has [1, 2, 3]
the returned vector must be [1, 2, 4]
like 123 + 1 = 124.
This is my code:
public class Solution { public ArrayList<Integer> plusOne(ArrayList<Integer> A) { int carry = 1; int length = A.size(); ArrayList result = new ArrayList(); for( int i = length - 1; i >=0; i-- ){ int val = A.get(i) + carry; result.add(0,val % 10); carry = val / 10; } if (carry == 1){ result.add(0,1); } for (int j = 0; j < result.size(); j++){ if(result.get(j).equals(0)) result.remove(j); else break; } return result; } }
However, in the test example: A: [0, 6, 0, 6, 4, 8, 8, 1]
he says my function returns
6 6 4 8 8 2
while the correct answer
6 0 6 4 8 8 2
I do not know what is wrong with my code.
Thanks!
source share