源代码
#include <iostream>
#include <cmath>
using namespace std;
template <typename T>
void Reverse(T a[], int begin, int end) {
for (int i = begin, j = end; i < j; i++, j--) {
T tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
template <typename T, const int N>
void Solve(T (&a)[N]) {
int times = log(N + 1) / log(2) + 1;
for (int i = 1; i <= times; i++) {
Reverse(a, pow(2, i - 1) - 1, pow(2, i) - 2);
}
}
int main() {
int a[] = {1, 2, 3, 4, 5, 6, 7};
Solve(a);
for (int i : a)
cout << i << ' ';
cout << endl;
return 0;
}
结果
1 3 2 7 6 5 4