Im stucked. :/ Write a method named stretch that accepts an array of integers as
ID: 3554308 • Letter: I
Question
Im stucked. :/
Write a method named stretch that accepts an array of integers as a parameter and returns a new array twice as large as the original, replacing every integer from the original array with a pair of integers, each half the original. If a number in the original array is odd, then the first number in the new pair should be one higher than the second so that the sum equals the original number. For example, if a variable named list refers to an array storing the values {18, 7, 4, 24, 11}, the call of stretch(list) should return a new array containing {9, 9, 4, 3, 2, 2, 12, 12, 6, 5>. (The number 18 is stretched into the pair 9, 9, the number 7 is stretched into 4, 3, the number 4 is stretched into 2, 2, the number 24 is stretched into 12, 12 and the number 11 is stretched into 6, 5.)Explanation / Answer
public static int[] stretch(int [] list){
int [] newlist=new int[list.length()*2];
for(int j=0;j<list.length();j++){
newlist[2*j]=list[j]/2+(list[j]%2);
newlist[2*j +1]=list[j]/2;
}
return newlist;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.