两道很有意思的面试题[转载]

两 道很有意思的面试题

http://www.cppblog.com/OnTheWay2008/archive/2010/03/28/110724.html第一题是:求一个字符串中出现频率最高的那个字符及其出现此时?
具体代码如下:
 1 void GetMost(char *pStr, char &ch, int &size)
 2 {
 3     ch = '\0';
 4     size = 0;
 5
 6     if (NULL != pStr)
 7      {
 8         int nArray[256];
 9         memset(nArray, 0, sizeof(nArray));
10
11         while(*pStr != '\0')
12          {
13             (nArray[*pStr + 128])+=1;
14             if((nArray[*pStr + 128]) > size)
15              {
16                 size = nArray[*pStr + 128];
17                 ch = *pStr;
18             }
19
20             pStr++;
21         }
22     }
23 }需要注意 char的范围是[-128,127]之间,所以数组下标要加上128!

第二道题是:把一个数提升到8的倍数。例如1需要提升 到8, 8提升之后还是8,11提升之后是16,23提升之后是24。
1 int GetUp2Eight(int nValue)
2 {
3     const int nEight = 8;
4     return (nValue + nEight - 1) & (~(nEight - 1));
5 }
这两道题的解法不太复杂,只是做法很巧妙。

你可能感兴趣的:(#链接文章)