Calculations with array list elements.

Total Post:27

Points:189
Java 
 1064  View(s)
Ratings:
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.
  1. Post:341

    Points:2389
    Re: Calculations with array list elements.

    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);
    }

      Modified On Apr-06-2018 01:29:51 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!