面试题1

大耳 2006-08-16 10:51:52
1 What is the fastest way to count the number of ones in a given number represented in a

binary form. You can assume that you have infinte run time memory and the response time

should be O(1) always. Can you optimize the memory used?


答案:

int bits_set( int word )
{
int tmp;

tmp = (word >> 1) & 033333333333;
tmp = word - tmp - ((tmp >> 1) & 033333333333);
return (((tmp + (tmp >> 3)) & 030707070707) % 077);

}

有人分析一下么?或者给个更好的解答:)
...全文
1090 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
xmdsrswl 2006-08-24
  • 打赏
  • 举报
回复
mark
大耳 2006-08-24
  • 打赏
  • 举报
回复
就是有些难以想通,不知他的工作原理
bohlee 2006-08-24
  • 打赏
  • 举报
回复
MARK
sharkoasis 2006-08-17
  • 打赏
  • 举报
回复
mark
qdhuxp 2006-08-17
  • 打赏
  • 举报
回复
mark
大耳 2006-08-16
  • 打赏
  • 举报
回复
2 What will be the complexity of finding the duplicates in an array?

3 You are given a stack of punched cards, each with m rows and n columns. Come up with a

algorithm to punch holes so that you can find the missing cards (their sequences) in O(1)

time. You can assume that you are looking for a missing card and only one is missing out of
all possibilities.

4 Write the binary search function in a C language.

5 In the given array, find the subsequence with maximum sum and minimum length.
E.g. [10,25,-23,40,-12,39,7] - The subsequence [39,7] has sum of 46 with length 2.

6 Reverse a linked list

7 Write an algorithm to compress a text file

8 How would you implement a BigInt class?

9 If you are given x punched cards each with m rows and n
columns, can u come up with a number scheme to identify missing
patterns.

10 An absolute number is defined as one in which each digit is
strictly smaller than the digit to its right (if any). For e.g. 123,
478, 369 are all absolute numbers. 205, 485 are not. Write a program
to calculate these.
cg5353 2006-08-16
  • 打赏
  • 举报
回复
sankt(黄景天) ( ) 信誉:110
int get_one_1(int x)
{
int countx = 0;
while(x)
{
++countx;
x = x & (x - 1);
}
return countx;
}
这个明显不是 O(1) 阿
Roxxette 2006-08-16
  • 打赏
  • 举报
回复
Question 1
int bits_seta(int w)
{
int t;
t = w - ((w>>1) & 0x55555555);
t = (t & 0x33333333) + ((t>>2) & 0x33333333);
t = (t + (t>>4)) & 0x0f0f0f0f;
t = (t + (t>>8)) & 0x00ff00ff;
t = (t + (t>>16)) & 0x0000ffff;
return t;
}
个人感觉是最优解了,运行一亿次平均时间1.45s,比lz的快1s
而且便于向64位移植-_-!
AdenPlus 2006-08-16
  • 打赏
  • 举报
回复
mark
sankt 2006-08-16
  • 打赏
  • 举报
回复
1 What is the fastest way to count the number of ones in a given number represented in a

binary form. You can assume that you have infinte run time memory and the response time

should be O(1) always. Can you optimize the memory used?

//========
int get_one_1(int x)
{
int countx = 0;
while(x)
{
++countx;
x = x & (x - 1);
}
return countx;
}
blue_zyb 2006-08-16
  • 打赏
  • 举报
回复
Question2:
If sufficient memory is given, then a O(N) complexity

69,364

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧