From: gobi on
Need help with one more question:

Implement:
int bits(unsigned char v);
Which returns number of set bits in v.

A) Optimize for memory usage:



B) Optimize for speed:


Thanks.
From: osmium on
"gobi" wrote:

> Need help with one more question:
>
> Implement:
> int bits(unsigned char v);
> Which returns number of set bits in v.
>
> A) Optimize for memory usage:
>
>
>
> B) Optimize for speed:

Assuming that there are 8 bits in a char, what kind of clever thing could
you do with a 256 element array?


From: Richard Heathfield on
gobi said:

> Need help with one more question:
>
> Implement:
> int bits(unsigned char v);
> Which returns number of set bits in v.
>
> A) Optimize for memory usage:

If you were to test the bottom bit (using % or &) and increment a
counter if that bit were set, and then shift right, and if you were
to continue doing so until you'd run out of set bits, do you think
that would do it?

> B) Optimize for speed:

See osmium's answer.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
This line unintentionally left unblank
From: Keith Thompson on
gobi <mk3lai(a)gmail.com> writes:
> Need help with one more question:
>
> Implement:
> int bits(unsigned char v);
> Which returns number of set bits in v.
>
> A) Optimize for memory usage:
>
> B) Optimize for speed:

C) Optimize for doing your own homework.

Give us your instructor's e-mail address so we can submit our
solutions directly.

--
Keith Thompson (The_Other_Keith) kst-u(a)mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"