blob: bb85ecd59f18482172380b307df7ba16cae9d052 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
#print
The problem is to produce a function
bitct(x)
which examines the bits in x, returning a count of
the number of 1-bits. There are various ways of doing
this job: here are two.
(1) a sane way. Shift the word x right 16 times (you are
on UNIX) and check the rightmost bit each time, counting
the number of times it is '1'.
(2) a machine-independent (sort of) way. The logical
bitwise AND of x and x-1 contains one fewer one bit than x itself.
Loop anding x and x-1 until you get zero.
Program either algorithm. Compile and test it. Leave it on
a file bitct.c and type "ready".
#once #create tzaqc.c
main()
{
int x;
x=23069;
if (bitct(x) != goodct(x))
return(1);
x=0;
if (bitct(x) != goodct(x))
return(1);
x=16384;
if (bitct(x) != goodct(x))
return(1);
x = -1;
if (bitct(x) != goodct(x))
return(1);
x= -200;
if (bitct(x) != goodct(x))
return(1);
return(0);
}
goodct(x)
{
int k, i;
for(k=i=0; i<16; i++)
{
k =+ (x&1);
x= x>>1;
}
return(k);
}
#user
cc tzaqc.c bitct.o
a.out
#succeed
/* a possible solution */
bitct(x)
{
int k, i;
for(i=k=0; i<16; i++) {
if (x&1)
k++;
x >>= 1;
}
return(k);
}
/* by the way, if you really care about
this problem a table lookup by whole bytes
is faster */
#log
#next
42.1a 10
|