Invertor#2098

Invertor (Editorial)

Store the numbers in a linear array. Then print them in reverse order.

Let’s consider a solution for reversing an array using the two-pointer technique.

Set two variables and (we'll call them pointers):

Next, start a while loop, in which:

We continue the loop until the pointers and meet.

Note that the values of and can be swapped using an additional variable by performing three operations:

Algorithm implementation

Read the input data.

scanf("%d",&n);
for(i = 0; i < n; i++)
  scanf("%d",&mas[i]);

Print the numbers in the reverse order.

for(i = n - 1; i >= 0; i--)
  printf("%d ",mas[i]);
printf("\n");

Algorithm implementation — reverse the array

Declare an array.

#define MAX 110
int m[MAX];

Read the input data.

scanf("%d",&n);
for(i = 1; i <= n; i++)
  scanf("%d",&m[i]);

Reverse the array using the two-pointer technique.

i = 1; j = n;
while(i < j)
{
  temp = m[i]; m[i] = m[j]; m[j] = temp;
  i++; j--;
}

Print the numbers.

for(i = 1; i <= n; i++)
  printf("%d ",m[i]);
printf("\n");

Algorithm implementation — STL reverse

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

int n, i;
vector<int> mas;

int main(void)
{
  scanf("%d",&n);
  mas.resize(n);
  for(i = 0; i < n; i++)
    scanf("%d",&mas[i]);

  reverse(mas.begin(),mas.end());

  for(i = 0; i < n; i++)
    printf("%d ",mas[i]);
  printf("\n");
  return 0;
}

Java implementation — print the array from right to left

import java.util.*;
 
public class Main
{
  public static void main(String[] args) 
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int mas[] = new int[n];
    for(int i = 0; i < n; i++)
      mas[i] = con.nextInt();
    
    for(int i = n - 1; i >= 0; i--)
      System.out.print(mas[i] + " ");
    System.out.println();
    con.close();
  }
}

Java implementation — reverse

import java.util.*;
 
public class Main
{
  public static void main(String[] args) 
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int m[] = new int[n];

    // Read data
    for(int i = 0; i < n; i++)
      m[i] = con.nextInt();

    // Reverse an array
    int i = 0, j = n - 1;
    while(i < j)
    {
      int temp = m[i]; m[i] = m[j]; m[j] = temp;
      i++; j--;
    }
    
    // Print the reversed array
    for(i = 0; i < n; i++)
      System.out.print(m[i] + " ");
    System.out.println();
    con.close();
  }
}

Python implementation

Read the input data.

n = int(input())
lst = list(map(int, input().split()))

Print the numbers in the reverse order.

for i in range(n - 1,-1,-1):
  print(lst[i], end = " ")

Python implementation — reverse

Read the input data.

n = int(input())
lst = list(map(int, input().split()))

Reverse the list using the reverse function.

lst.reverse()

Print the reversed list.

print(*lst)