ArrayList Removing the first item

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!

+6
source share
3 answers
 if(result.get(j).equals(0)) result.remove(j); else break; 

This will fail if every other index contains 0. Here's what happens:

 0 6 0 6 4 8 8 2 ^ (j = 0) 

0 will be deleted and j will be increased by one.

 6 0 6 4 8 8 2 ^ (j = 1) 

Then this 0 is also removed, skipping the first 6 in your array. To fix this, change the snippet to:

 if(result.get(j).equals(0)) result.remove(j--); else break; 

This compensates when the index is deleted, so j will not skip the number immediately after all deleted 0s.

+7
source

Highlight a similar question in Looping through and arraylist and delete items at the specified index

easier to do only

 while (!result.isEmpty() && result.get(0).equals(0)) { result.remove(0); } 

This will delete the leftmost 0 until there is no more than zero left to be deleted.

0
source

Your last for loop removes 0 from your ArrayList<Integer> result. After removing this loop you will get a great result

 public static 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; //2 8 result.add(0, val % 10); // 2 8 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; // } for (boolean isZero = true; isZero; ) { isZero = result.get(0).equals(0); if(isZero) result.remove(0); } return result; } 
0
source

Source: https://habr.com/ru/post/987100/


All Articles