+ 1
how can we slove this static method ? help me out
Write a static method named stretch that accepts an array of integers as a parameter and returns a new array as twice as the original, replacing every integer from the original array with a pair of integers each half of the original. If a number in the original array is odd then first number in the new array should be higher then the second so the sum equals the original number. For example if a list contains following values {18,9,6,28,13}, the call of the stretch function should create the new array as following {9,9,5,4,3,3,14,14,7,6}.
4 Respostas
+ 1
import java.util.*;
public class TestStretch {
public static void main(String[] args) {
int[] list = {18, 7, 4, 14, 11};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list)); // [18, 7, 4, 24, 11]
System.out.println(Arrays.toString(list2)); // [9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
}
public static int[] stretch(int[] array){
int length = array.length;
int[] newArray = new int[array.length*2];
for(int i = 0; i< length; i=i+2){
int j = 0;
if(array[i] % 2 == 0){
newArray[i] = (array[j]/2);
newArray[i+1] = newArray[i];
j++;
} else{
newArray[i] = (array[j]/2);
newArray[i+1] = (newArray[i] + 1);
j++;
}
}
return newArray;
}
}
but i m getting output
(9,9,9,9,9,9,10,0,0,0)
instead of
(9,9,5,4,3,2,2,7,7,6,5
+ 1
javascritpt
0
which language ?
0
With JavaScript, use Array.prototype.reduce()
https://code.sololearn.com/WjgLoufudDRF/?ref=app