Friday, September 1, 2017

Complete Array reverse Method

An array of N integers is passed as the input to the program and the program must print the array after reversing it. Complete the method reverse so that the program can execute successfully.

Input Format:
The first line contains N. The second line contains N integer values each separated by a space.

Output Format:
The first line contains reversed values of N integers separated by a space.

Boundary Conditions:
1 <= N <= 1000

Example Input/Output 1:
Input:
5
10 22 33 45 600
Output:
600 45 33 22 10

Solution-1:
def reverse(nums):
    return nums[::-1]
N = int(input())
nums = list(map(int, input().strip().split()))
reversednums = reverse(nums)
for num in reversednums:
print (num, end=' ')

Solution-2:
def reverse(nums):
    i,j=0,len(nums)-1
    while i<j:
        nums[i],nums[j]=nums[j],nums[i]
        i+=1
        j-=1
    return nums
N = int(input())
nums = list(map(int, input().strip().split()))
reversednums = reverse(nums)
for num in reversednums:
print (num, end=' ')
Share: