0

Hi everyone I am currently trying to convert a string to an arrayList in reverse and then remove any trailing zeros eg "001203" converts to (3,0.2,1,0,0) and then (3,0,2,1)

my code is currently

public convert(String nums) {
    List = new ArrayList<Integer>();  // create arraylist

    for (int i = nums.length(); i >= 0; i--) { //convert to int
        int j = Integer.parseInt(digits);
        List .add(j);

        for (Iterator<Integer> k = List .iterator(); k.hasNext();) {  //remove trailing zeros
            if (k.next().equals(0)) {
                k.remove();
            }
        }

    }

This code currently removes all 0s instead of the trailing zeros. meaning my output is (3,2,1) instead of (3,0,2,1);

any help will be appreciated thanks in advance

4
  • 2
    Begin your iteration at the end of your array. Remove zeros until a non-zero is found, at which point you should break the loop Commented May 22, 2015 at 13:32
  • 1
    how is "001203" getting converted to 3, 0.2?, 1, 0, 0 is this a typo? Commented May 22, 2015 at 13:33
  • Try to write a method that will trim zeroes like this : Find first non 0, that's the start of new string, and second value is last appearance of non 0 character, after that You can use String.subString(start, end) ;) That way you'll ensure correct return. Your way is removing every 0 from string. Commented May 22, 2015 at 13:34
  • @gtgaxiola yes it is a typo Commented May 22, 2015 at 13:51

3 Answers 3

1

The problem with your method is that, in your inner loop, you're removing zeroes regardless of its position in the list.

There are multiple ways to achieve what you want. Here's one method using a single loop (without String or Collections operations that reverse your list for you):

    String nums = "001203";

    List<Integer> list = new ArrayList<>();

    // a boolean flag to help check for leading zeroes
    // set it to true first i.e. assume there are leading zeroes
    boolean checkLeadingZeroes = true;

    // Ignore leading zeroes during iteration,
    // and append to list in reverse order

    for (int i=0; i < nums.length(); i++){
        int n = Integer.parseInt(nums.charAt(i)+"");

        // only check for leading zeroes if flag is true

        if (checkLeadingZeroes){
            // If flag is set to false here, you've found the first non-zero

            checkLeadingZeroes = (n == 0);
        }

        if (!checkLeadingZeroes) {
            /* If flag is false, n is not a leading zero
             * Add n to the beginning of your list (index 0)
             */
            list.add(0, n);
        }
    }

A couple of other options:

  1. Change your inner loop so that you iterate backwards on your list, and remove zeroes until you find a non-zero value

  2. Trim all leading zeroes first (e.g. using a regex operation, or a loop), then loop backwards to create your list.

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this code :

public static void main(String[] args) {
     String numStr = "001203";
     String revNumStr = new StringBuilder(numStr).reverse().toString();

     int lastZeroIndex = revNumStr.lastIndexOf('0');
     if(lastZeroIndex == revNumStr.length() - 1) {
         String newStr = "";
         boolean done = false;
         for(int i = (revNumStr.length() - 1) ; i >= 0 ; i --) {

             if(revNumStr.charAt(i) != '0') {
                done = true; 
             }

             if(done) {
                 newStr += revNumStr.charAt(i);
             }
         }

         revNumStr = new StringBuilder(newStr).reverse().toString();
     }

     System.out.println("The revrese string is : " + revNumStr);
}

Comments

0

Here's a quick example of what you want to do shortly:

String example =  "001203";
// Replacing all leading 0s with empty, converting to char array
char[] chars = example.replaceAll("^0+", "").toCharArray();
// creating list of integers
List<Integer> list = new ArrayList<Integer>();
// iterating chars
for (char c: chars) {
    // trying to convert to integer
    try {
        list.add(Integer.parseInt(Character.toString(c)));
    }
    catch (NumberFormatException nfe) {
        // TODO handle non-numeric characters!
    }
}
// reversing list
Collections.reverse(list);
// printing list
System.out.println(list);

Output

[3, 0, 2, 1]

Note

Another option, without using Collections.reverse, is to start the iteration at the end of your char[]:

for (int i = chars.length - 1; i > -1; i--) {
    try {
        list.add(Integer.parseInt(Character.toString(chars[i])));
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.