Given an array, the task is to reverse the array without using subtract sign ‘-‘ anywhere in your code. It is not tough to reverse an array but the main thing is to note use ‘-‘ operator.
Asked in: Moonfrog Interview
Below are different approaches:
1- Store array elements into a vector in C++.
2- Then reverse the vector using predefined functions.
3- Then store reversed elements into the array back.
1- Store array elements into a stack.
2- As the stack follows Last In First Out, so we can store elements from
top of the stack into the array which will be itself in a reverse manner.
1- In this method the idea is to use negative sign but by storing it into a variable.
2- By using this statement x = (INT_MIN/INT_MAX), we get -1 in a variable x.
3- As INT_MIN and INT_MAX have same values just of opposite signs,so on dividing them it will give -1.
4- Then ‘x’ can be used in decrementing the index from last.
6 1 2 7 3 5
In this method 4, the idea is to use bitwise operator to implement subtraction i.e.
A – B = A + ~B + 1
so, i– can be written as i = i +~1 +1
6 1 2 7 3 5
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum number of subtract operation to make an array decreasing
- Sort an array where a subarray of a sorted array is in reverse order
- First string from the given array whose reverse is also present in the same array
- Perl | Reverse an array
- Reverse an array upto a given position
- Reverse an array in groups of given size
- Program to reverse an array using pointers
- Sorting array with reverse around middle
- C Program to Reverse Array of Strings
- Write a program to reverse an array or string
- Reverse an array in groups of given size | Set 2 (Variations of Set 1 )
- Reverse an array without affecting special characters
- Program to copy the contents of one array into another in the reverse order
- Print all the combinations of N elements by changing sign such that their sum is divisible by M
- Subtract 1 without arithmetic operators