第一题:
其中,reverse函数的代码实现如下:
1.
unsigned int reverse(unsigned int num)
{
unsigned int ans = 0;
for (int i = 0; i <= 31; i++) {
num = num >> 1;
int tmp = num & mask;
if (tmp == 1)
ans += pow(2,31-i);
}
return ans;
}
2.
unsigned int reverse(unsigned int num)
{
unsigned int ans = 0;
int i = 0;
while (num != 0) {
int tmp = num & 0x1;
if (tmp == 1)
ans += pow(2,31-i);
i++;
num >>= 1;
}
return ans;
}
第二题:编程填空题,考察堆排序。
代码如下:
static void heap_arrange(int arr[], int cur, int cnt) //调整为小顶堆 { int heaptop_val = arr[cur]; //堆顶的值 while (cur < cnt) { int left = 2 * cur + 1; int right = 2 * cur + 2; int min = -1; int min_val =heaptop_val; if (left < cnt && arr[left] < min_val) { //检查是否比左节点大 min = left; min_val = arr[left]; } if (right < cnt && arr[right] < min_val) {//检查是否比右节点大 min = right; } if (min == -1) break; arr[cur] = arr[min]; cur = min; } arr[cur] = heaptop_val; }