Given an array of n integers. Print only its negative elements,
reversing their order.
Input. The first line
contains the integer n (1 ≤ n ≤ 100). The second line
contains n integers, each with an absolute value not exceeding 100.
Output. On the first line,
print the number of negative elements in the array.
On the second line, print the negative elements in reverse order. If there are
no negative elements in the array, print “NO”.
Sample input 1 |
Sample output 1 |
7 -2 5 4 -3 7
-1 0 |
3 -1 -3 -2 |
|
|
Sample input 2 |
Sample output 2 |
5 2 1 0 1 5 |
NO |
array
Algorithm analysis
Read the
input sequence into an array. Count the
number of negative elements. If there
are no negative numbers (the count is 0),
print “NO”.
Otherwise, first print the count of negative numbers, followed by the numbers themselves
in reverse order.
Algorithm implementation
To store
the sequence, declare an array m.
int m[101];
Read the input data.
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &m[i]);
Count the
number of negative elements in the
variable cnt.
cnt = 0;
for (i = 0; i < n; i++)
if (m[i] < 0) cnt++;
If there are no negative numbers in the array, print “NO”.
if (cnt == 0)
printf("NO\n");
else
{
Print the count
of negative numbers.
printf("%d\n", cnt);
Print the
negative numbers in reverse order.
for (i = n - 1; i >= 0;
i--)
if (m[i] < 0) printf("%d ", m[i]);
printf("\n");
}
Python implementation
Read the input data.
n = int(input())
lst = list(map(int, input().split()))
Create a list negatives that contains only
the negative numbers.
negatives = [x for x in
lst if x < 0]
If there are no negative numbers in the array, print “NO”.
if not negatives:
print("NO")
else:
Otherwise, first print the count of
negative numbers, followed by the negative numbers in reverse order.
print(len(negatives))
print(*negatives[::-1])