k&r : finished chapter 2
parent
e001baa96f
commit
abccef71d3
|
@ -0,0 +1,35 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "02-bitwise.h"
|
||||
|
||||
int bitcount(unsigned x);
|
||||
|
||||
/* parse command line args for bitcount, print result */
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
if (argc < 2) {
|
||||
printf("error : expected argument x\n");
|
||||
return 1;
|
||||
}
|
||||
unsigned x;
|
||||
if (!int_of_string(&x, argv[1]))
|
||||
return 2;
|
||||
|
||||
printf("%d\n", bitcount(x));
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* x &= x-1 deletes the right most 1 bit
|
||||
* suppose x = y10..0
|
||||
* then x-1 = y01..1
|
||||
* then x & x-1 = y00..0
|
||||
* QED */
|
||||
|
||||
/* bitcount: count number of set bits in x, using the abova property */
|
||||
int bitcount(unsigned x)
|
||||
{
|
||||
int b;
|
||||
for (b = 0; x; b++)
|
||||
x &= x-1;
|
||||
return b;
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
#include <stdio.h>
|
||||
|
||||
char lower(char c);
|
||||
|
||||
int main()
|
||||
{
|
||||
int c;
|
||||
while ((c = getchar()) != EOF)
|
||||
putchar(lower(c));
|
||||
return 0;
|
||||
}
|
||||
|
||||
char lower(char c)
|
||||
{
|
||||
return (c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c;
|
||||
}
|
Loading…
Reference in New Issue