劍指offer——第一章(C++實現)
阿新 • • 發佈:2018-11-13
寫在前面的話
面試官會關注邊界條件、特殊輸入(如nullptr指標、空字串等)以及錯誤處理。
題目1:把一個字串轉換成整數
邊界條件:
1)考慮到輸入的字串中有非數字字元和正負號
2)要考慮到最大的正整數和最小的負整數以及溢位
3)考慮到當輸入的字串不能轉換成整數時,應該如何做錯誤處理。
實現程式碼:
#include <iostream> #include<string> int StrToInt(std::string input) { int len = input.length(), str_index=0; int positive_num = 0, negative_num = 0; if (len == 0) return 0; long long answer = 0; //去除字串前置空格 while (input[str_index] == ' ') str_index++; //正負號判斷 if (input[str_index] == '+') { positive_num++; str_index++; } else if (input[str_index] == '-') { negative_num++; str_index++; } for (; str_index < len; str_index++) { if (input[str_index] >= '0' && input[str_index] <= '9') { answer = answer * 10 + input[str_index] - '0'; //溢位判斷 if (positive_num && (answer>= 2147483647)) { return 2147483647; } if (negative_num && (answer >= 2147483648)) { return -2147483648; } } else{ return 0; } } return negative_num ? -answer: answer; } int main() { printf("請輸入字串:\n"); std::string input; //讀取一行字串 getline(std::cin, input); int answer = StrToInt(input); printf("%d\n", answer); system("pause"); return 0; }
小技巧:
c++語言,cin和cout的比scanf和printf更耗時。所以,線上筆試的時候,多用後者。或者新增下圖中的函式
題目2:求連結串列中的導數第k個節點
邊界條件:
1、判斷輸入的指標是否為空
2、連結串列節點數是否小於k
3、k的值是否為0
實現程式碼:
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if ((pListHead == nullptr) || (k == 0)) return nullptr; ListNode *fast = pListHead, *slow = pListHead; //快指標移動k-1步,使其移動到連結串列第k個節點的位置 while ((fast->next != nullptr) && (k-1 > 0)) { fast = fast->next; k--; } //此時快指標移動到了連結串列第k個節點的位置 if ((k == 1) && (fast->next != nullptr)) { while (fast->next != nullptr) { fast = fast->next; slow = slow->next; } return slow; } //此時快指標沒有移動到連結串列第k個節點的位置(連結串列長度小於k) else if ((fast->next == nullptr) && (k > 1)){ return nullptr; } //k節點為連結串列頭節點 else{ return pListHead; } } };