第一题,关键字:字符串翻转
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个相同的玻璃小球,小球从高于一定的高度摔下会被摔碎,请设计一种策略,要求尝试最少的次数就可以找到小球被摔碎的高度阀值。
这个题已有答案,待有时间时再写分析。