###一些课后习题
#####练习2-9. 在求对二的补码时,表达式 x&=(x-1)可以删除x中最右边值为1的一个二进制位。请解释这样做的道理。用这一方法重写bitcount函数,以加快其执行的速度。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int x = atoi(argv[1]);
int y = x;
int count = 0;
while(y != 0){
y&=y-1;
count++;
}
printf("bitcount(%d) = %d\n", x,count);
}
#####练习2-10. 重新编写将大写字母转换为小写字母的函数lower,并用条件表达式替代其中的if-else结构。
#include <stdio.h>
char *lower(char *s);
int main(int argc, char *argv[]){
char *s = argv[1];
lower(s);
printf("\n");
}
char *lower(char *s){
while(*s != 0){
int ch = *s;
printf("%c", ((ch >= 'A') && (ch <= 'Z')) ? ch += 32 : ch);
s++;
}
return s;
}