We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Saw a lot of code that prints the array just in reverse which is a perfect solution for this problem. If you want to actually reverse the array in your code and use it further I implemented the reversal with a xor swap. This way you don't need a temporary array or variable.
include
include
int main()
{
int num, arr, i;
scanf("%d", &num);
arr = (int) malloc(num * sizeof(int));
for(i = 0; i < num; i++) {
scanf("%d", arr + i);
}
/* Write the logic to reverse the array. */
// reverse array using xor swap
for(i = 0; i < num / 2; i++) {
// implement xor swap
// a, b
// a = a^b
// b = a^b
// a = a^b
// a and b values are swapped
arr[i] = arr[i] ^ arr[num - i - 1];
arr[num - i - 1] = arr[i] ^ arr[num - i - 1];
arr[i] = arr[i] ^ arr[num - i - 1];
}
for(i = 0; i < num; i++)
printf("%d ", *(arr + i));
free(arr);
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Array Reversal
You are viewing a single comment's thread. Return to all comments →
Saw a lot of code that prints the array just in reverse which is a perfect solution for this problem. If you want to actually reverse the array in your code and use it further I implemented the reversal with a xor swap. This way you don't need a temporary array or variable.
include
include
int main() { int num, arr, i; scanf("%d", &num); arr = (int) malloc(num * sizeof(int)); for(i = 0; i < num; i++) { scanf("%d", arr + i); }
}