本篇記錄了兩道關于位運算的選擇題,和一道有點思維的代碼題。
C語言碎片知識
求函數返回值,傳入 -1 ,則在64位機器上函數返回( )
int func(int x) {int count = 0;while (x){count++;x = x&(x - 1);//與運算} return count; }
A: 死循環 B: 64 C: 32 D: 16
答案:C
int類型占四個字節即32位,-1的補碼是32個1,x=x&(x-1)的作用是每次將右邊的1變為0,一共執行32次。
讀代碼選結果( )
int count = 0; int x = -1; while(x) {count++;x = x >> 1; } printf("%d",count);
A: 1 B: 2 C: 32 D: 死循環,沒結果
答案:D
有符號數右移運算高位是補符號位的,負數的符號位是1,所以x永遠不會變為0,是個死循環。
每日代碼
找到所有數組中消失的數
. - 力扣(LeetCode)
/*** Note: The returned array must be malloced, assume caller calls free().*/
int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {for (int i = 0; i < numsSize; i++) {if (nums[abs(nums[i]) - 1] > 0) {nums[abs(nums[i]) - 1] *= -1;}}int* ans = (int*)malloc(sizeof(int) * numsSize);int pos = 0;for (int i = 0; i < numsSize; ++i) {if (nums[i] > 0) {ans[pos++] = i + 1;}}*returnSize = pos;return ans;
}
將nums[出現過的數字]所對應的值改為負數,這樣最后所剩的正數的下標就是缺失的數。
-The End-