Home > DeveloperSection > Forums > Calculations with array list elements.
Lillian Martin

Total Post:27

Points:189
Posted on    October-29-2014 12:23 AM

 Java Java 
Ratings:


 1 Reply(s)
 540  View(s)
Rate this:
I have an integer array list. It will always contain 5 integers. Now suppose it contains the numbers 10031. Now I want to do this calculation in the elements.

Add the numbers within this number, until you are left with a 1 or 2 digit number.

1.....0.....0.....3.....1

...1.....0......3....4

.......1.....3.....7

...........4....10 (When this occurs, separate into 1 + 0)

..............5..1 = 51. Result is 51.

I want the result when it is a double digit number. Please help.


Ankit Singh

Total Post:341

Points:2389
Posted on    October-29-2014 12:24 AM

try this:

public static int yourFunction(ArrayList<Integer> list){

    String numbers = "";

 

    for(Integer i : list){

        numbers += String.valueOf(i);

    }

 

    String tmp_numbers;

    while(numbers.length() > 2){

        tmp_numbers = "";

        for(int i = 0; i < numbers.length()-1; ++i){

 

            int v = Integer.parseInt(numbers.substring(i,i+1));

                v += Integer.parseInt(numbers.substring(i+1,i+2));

            tmp_numbers = tmp_numbers + String.valueOf(v);

        }

        numbers = tmp_numbers;

    }

    return Integer.parseInt(numbers);

}


Don't want to miss updates? Please click the below button!

Follow MindStick