第一題,關鍵字:字符串翻轉
Reverse the words in a given English sentence (string) in C or C++ without requiring a separate buffer to hold the reversed string (programming)
For example:
Input: REALLY DOGSDISLIKE MONKEYS
Output: MONKEYS DISLIKEDOGS REALLY
My code is
- void reverse_string (char *s, int start, int end)
- {
- // be sure that start is less than end
- if (start >= end)
- return;
- char tmp;
- while (start < end) {
- tmp = *(s + start);
- *(s + start) = *(s + end);
- *(s + end) = tmp;
- start++, end--;
- }
- }
- void reverse_sentence (char *s, int n)
- {
- reverse_string(s, 0, n-1);
- int start;
- bool in_word = false;
- for (int i=0; i<=n; i++)
- {
- if (*(s+i) == ' ' || *(s+i) == '\0')
- {
- if (in_word)
- reverse_string(s, start, i-1);
- in_word = false;
- } else if (!in_word)
- {
- in_word = true;
- start = i;
- }
- }
- }
- int string_len (const char *s)
- {
- int i = 0;
- while (*(s+i++) != '\0');
- return i-1;
- }
- void test_reverse_sentence ()
- {
- char s[] = "REALLY DOGSDISLIKE MONKEYS";
- reverse_sentence (s, string_len(s));
- std::cout << s;
- }
第二題,關於如何洗牌的一道算法題,關鍵字:隨機數生成
Write a program to shuffle a deck of 52 cards, which is stored in an array and print the shuffle result
My Code:
- void shuffle_deck ()
- {
- char deck[52];
- // Clear the array, set as zero.
- memset(deck, 0, 52);
- int loc;
- // Use number 1,2,..52 represent 52 deck cards.
- for (int i=1; i<=52; i++)
- {
- do {
- loc = rand() % 52;
- } while (deck[loc] != 0);
- deck[loc] = i;
- }
- // Print the shuffle result.
- for (int i=0; i<52; i++) {
- printf ("%d ", deck[i]);
- }
- }
第三題,這是微軟電話面試中的一道題,利用一個循環想將一個浮點數增加2^32次,下面的代碼可以實現嗎?
|
第四題,這是微軟電話面試中的另外一道題,設計一個算法,對給定的任意一個字節實現按比特位翻轉,要求算法的時間複雜度爲O(1)。
實現字節按比特位翻轉的算法不難,難的是滿足時間複雜度爲O(1)。其實思想很簡單,就是用空間換時間,因爲一個比特位要麼是0,要麼是1,因此一個字節8個比特位也就256種可能性,是可枚舉的,只要建立一張包含所有可能的比特位翻轉映射表就可以了。
第五題, 這是在codility種遇到的一個問題,在一個整型數組種找平衡點的問題,具體需要再分析。
第六題,微軟電話面試中的另外一道題,100階樓梯,每階樓梯的高度是不同的,但是是依次遞減的,給2個相同的玻璃小球,小球從高於一定的高度摔下會被摔碎,請設計一種策略,要求嘗試最少的次數就可以找到小球被摔碎的高度閥值。
這個題已有答案,待有時間時再寫分析。