經典筆試集錦

來源:互聯網
上載者:User
1)
#include <stdio.h>int i = 1;int main(int argc, char* argv[]){ int i = i; printf("%d \n",i); return 0;}

可以猜想到底輸出什麼東東,其實在main裡面,因為申明了i變數,所以main函數裡面的i不是外面的i,然而i並未初始化,故i的值是沒有定義的。

2)

int fun(int x){  int count=0; while(x){    count++;    x=x&(x-1);} return count;}

需要搞清這個函數是幹嘛的?

   x=x&(x-1);這個東東才是主要的,所做的事情就是把x的二進位從右至左將1置為0.所以這個函數就是數x的二進位中的1的個數的

3)判斷一個數(x)是否是2的n次方

#include <stdio.h>int func(int x){    if( (x&(x-1)) == 0 )        return 1;    else        return 0;}int main(){    int x = 8;    printf("%d\n", func(x));}

注: 如果一個數是2的n次方,那麼這個數用二進位表示時其最高位為1,其餘位為0。

4)

             unsigned char a=0xa5;

unsigned char b=~a>>4+1;printf("%d\n",b);
以下是反組譯碼代碼:
     unsigned char a=0xa5;00401056 C6 45 F0 A5          mov         byte ptr [ebp-10h],0A5h     unsigned char b=~a>>4+1;0040105A 8B 45 F0             mov         eax,dword ptr [ebp-10h]0040105D 25 FF 00 00 00       and         eax,0FFh00401062 F7 D0                not         eax00401064 C1 F8 05             sar         eax,500401067 88 45 EC             mov         byte ptr [ebp-14h],al      printf("%d\n",b);0040106A 8B 4D EC             mov         ecx,dword ptr [ebp-14h]0040106D 81 E1 FF 00 00 00    and         ecx,0FFh00401073 51                   push        ecx00401074 68 1C 50 43 00       push        offset string "%d\n" (0043501c)00401079 E8 02 71 00 00       call        printf (00408180)0040107E 83 C4 08             add         esp,8

看到彙編代碼,一目瞭然。可以看出,and、not等操作是在eax中進行,not操作會使得其高位都取反,再右移則會使得eax為FF FF FF FA。

最後在printf參數壓棧時會取低8位而已:and         ecx,0FFh。

5)

int f(int x,int y)
{
  return (x&y)+((x^y)>>1);
}

細細評味,可以看出,這是在求x+y的一半哦


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.