0

I am trying to achieve the following:

Given a list {146,7,-2,-1} write a new list such that its ith element consists of sums of "i" and i+1".

So this list: {146,153,151,150} would be transformed into 146 as 146+7=153, 153+(-2)=151 and so on. I wrote the following:

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

list2.add(0, list.get(0));

for(int i=0;i<list.size()-1;i++)
{
  list2.add(i+1, list.get(i+1)+list.get(i));
  System.out.println(list2);
}

However, this is returning {146,153,6,-3}. What I am doing wrong?

1 Answer 1

3

You should be adding to list2.get(i) instead of list.get(i)

List<Integer> list = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
list2.add(0, list.get(0));

for(int i=0;i<list.size()-1;i++)
{
    list2.add(i+1, list.get(i+1)+list2.get(i));
    System.out.println(list2);

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

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.