百度筆試之1KB內存,1MHz處理器 運行最長時間 maxContinuNum

問題一:如果你有一臺迷你電腦,有1KB內存,1MHz處理器(每秒可處理10 ^6次狀態改變)。求能夠在這上運行且確定性終止的所有程序中,最長運行時間可能是多少?給出思路及推理過程(可以做任何假設)。

 

1KB內存 ≈1000Byte ≈ 8000bit 一共有2^8000個可能狀態

 

所以答案爲:2^8000/10^6

 

 

問題二:int maxContinuNum(const char *inputstr,char *outputstr)

功能:在以'/0'結尾的字符串中找出連續最大的數字串,並返回其長度,把這個最長數字串賦給其中一個函數參數outputstr所指的內存。如調用maxnumstr("123abc1234a", outputstr)後返回4outputstr中爲"1234"

要求:不能使用系統函數或標準庫提供的函數,如strlen之類的庫函數。

 

 

解決方法:

int maxContinuNum(const char* inputstr, char *outputstr)

{

    int count1,count2;

    char frontchar;

    char *tempstr1,*tempstr3;

    char* tempstr2 = new char[200];

    char* destr;

    destr = tempstr2;

    //strcpy(tempstr2,inputstr);

    if(outputstr!=NULL)

    {

       while((*tempstr2++ = *inputstr++)!='/0');

       tempstr2 = destr;

 

    }

 

 

    count1 = 0;

    count2 = 0;

    if(*tempstr2 == '/0')

       return 0;

    frontchar = *tempstr2;

    if(frontchar>='0'&&frontchar<='9')

    {

       count2 = 1;

       tempstr1 = tempstr2;

       outputstr = tempstr1;

    }

    tempstr2++;

    while(*tempstr2 != '/0')

    {

       if(*tempstr2>='0'&&*tempstr2<='9'&& 1==(*tempstr2-frontchar))

       {

           count2++;    

 

       }

       else if(*tempstr2>='0'&&*tempstr2<='9')

       {

           if(count2>count1)

           {

              count1 = count2;

              outputstr = tempstr1;

           }

              count2 = 1;

              tempstr1 = tempstr2;       

       }     

       else

       {

           if(count2>count1)

           {

              count1 = count2;

              outputstr = tempstr1;

           }

           count2 = 0;  

        }

       frontchar = *tempstr2;

       tempstr2++;

    }

    if(count2>count1)

    {

       count1 = count2;

       outputstr = tempstr1;

    }

    tempstr3 = outputstr;

    for(int i=0; i<count1;i++)

    {

       tempstr3++;

    }

    *tempstr3 = '/0';

    return count1;

}

 

 

這道題最初看似考察指針 字符串的一些問題 但是其中另藏玄機 

const char *轉換爲 char*纔是最容易被忽視的難點 一般而言 需要使用strcpy這個系統函數 但是由於題目限制 所以需要另外寫一個strcpy函數 其他的難度就不是很大 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章