Pages

Double the first element and move zero to end

Double the first element and move zeros to the end of array

  • For a given integer array, assume '0' is an invalid number and all other valid numbers. Convert to array such that if current and next values are same, then double the current value and make next value as 0. After shift all zero's to the right of the array.
Examples:

Input: { 2, 2, 0, 4, 0, 8 }
o/p:     4 4 8 0 0 0

Input: {0, 2, 2, 2, 0, 6, 6, 0, 0, 8}
o/p:   4 2 12 8 0 0 0 0 0 0

Program:
public class doubleElementMoveZeroEnd {
public static void main(String[] args) {
int[] arr = { 2, 2, 0, 4, 0, 8 };
// op: 4 0 0 4 0 8
// after moving zeros to end of array
// op: 4 4 8 0 0 0
for (int i = 0; i < arr.length - 1; i++) {
// if true, perform the required modification
if ((arr[i] != 0) && (arr[i] == arr[i + 1])) {
// double current index value
arr[i] = 2 * arr[i];
// put 0 in the next index
arr[i + 1] = 0;
// increment by 1 so as to move two
// indexes ahead during loop iteration
i++;
}
}

System.out.println(
"Array after Double the first element = ");
for (int n : arr) {
System.out.
print(n + " ");
}

System.out.println(
"\nArray after Double the first element and moving zeros to end= ");
int
temp;

for (int i = 0; i <= arr.length - 1; i++) {
for (int j = i + 1; j <= arr.length - 1; j++) {
if (arr[i] == 0) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

for (int n : arr) {
System.out.
print(n + " ");
}
}
}
Output:
Double the first element and move zero to end
Double the first element and move zero to end

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.