题目源自July的博客http://blog.youkuaiyun.com/v_JULY_v?viewmode=contents
28.整数的二进制表示中1的个数(运算)
题目:输入一个整数,求该整数的二进制表达中有多少个1。
例如输入10,由于其二进制表示为1010,有两个1,因此输出2。
分析:
这是一道很基本的考查位运算的面试题。
包括微软在内的很多公司都曾采用过这道题。
#include <assert.h>
#include <stdio.h>
int countLetterOne(unsigned int num){
int total=0;
int i;
for(i=0;i<32;i++){
int b=0x1<<i;
int test=b#
if(test!=0){
total++;
}
}
return total;
}
int main(){
int len;
unsigned int test=255;
len=countLetterOne(test);
printf("%d\n",len);
return 0;
}
26.左旋转字符串
题目:
定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。
如把字符串abcdef 左旋转2 位得到字符串cdefab。请实现字符串左旋转的函数。
要求时间对长度为n 的字符串操作的复杂度为O(n),辅助内存为O(1)。
#include <stdio.h>
#include <assert.h>
char *leftRotate(char *str,int len,int n){
assert(n<=len);
int i;
for(i=0;i<n;i++){
char tmp=str[0];
int j;
for(j=0;j<len-1;j++){
str[j]=str[j+1];
}
str[j]=tmp;
}
return str;
}
int main(){
char test[]="abcdef";
leftRotate(test,6,2);
printf("%s\n",test);
return 0;
}
第21题
2010年中兴面试题
编程求解:
输入两个整数 n 和 m,从数列1,2,3.......n 中 随意取几个数,
使其和等于 m ,要求将其中所有的可能组合列出来.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#define LEN 100
typedef struct _MyStack{
int num[LEN]; /*here we assume the max of n is 100 */
int top;
}MyStack;
void printStack(MyStack *s){
int i;
for(i=0;i<=s->top;i++){
printf("%d\t",s->num[i]);
}
printf("\n");
}
void initStack(MyStack *s){
s->top=-1;
memset(s->num,0,LEN);
}
void push(int val,MyStack *s){
if(s->top>=LEN-1){
printf("the stack is full\n");
exit(-1);
}
s->top++;
s->num[s->top]=val;
}
int pop(MyStack *s){
if(s->top==-1){
printf("the stack is empty\n");
exit(-1);
}
int ret=s->num[s->top];
s->top--;
return ret;
}
int sumStack(MyStack *s){
int i;
int sum=0;
for(i=0;i<=s->top;i++){
sum+=s->num[i];
}
return sum;
}
int isEmpty(MyStack *s){
if(s->top==-1){
return 1;
}
else{
return 0;
}
}
void find(int n,int m){
int total=n*(n+1)/2;
if(m<1||m>total){
printf("no one match\n");
return ;
}
MyStack s;
int i;
for(i=1;i<=n;i++){
initStack(&s);
int j=i;
while(j<=n){
push(j,&s);
int test=sumStack(&s);
if(test<m){/*if test <m ,prepare to push the next j */
j++;
}
else{
if(test==m){
printStack(&s);
}
pop(&s);
if(isEmpty(&s)){
break;
}
int topval=pop(&s);
if(isEmpty(&s)){
break;
}
else{
j=topval+1;
}
}
}
}
}
int main(){
find(7,7);
return 0;
}