Tracks
/
PHP
PHP
/
Exercises
/
Eliud's Eggs
Eliud's Eggs

Eliud's Eggs

Medium

Introduction

Your friend Eliud inherited a farm from her grandma Tigist. Her granny was an inventor and had a tendency to build things in an overly complicated manner. The chicken coop has a digital display showing an encoded number representing the positions of all eggs that could be picked up.

Eliud is asking you to write a program that shows the actual number of eggs in the coop.

The position information encoding is calculated as follows:

  1. Scan the potential egg-laying spots and mark down a 1 for an existing egg or a 0 for an empty spot.
  2. Convert the number from binary to decimal.
  3. Show the result on the display.

Example 1:

Chicken Coop:
 _ _ _ _ _ _ _
|E| |E|E| | |E|

Resulting Binary:
 1 0 1 1 0 0 1

Decimal number on the display:
89

Actual eggs in the coop:
4

Example 2:

Chicken Coop:
 _ _ _ _ _ _ _ _
| | | |E| | | | |

Resulting Binary:
 0 0 0 1 0 0 0 0

Decimal number on the display:
16

Actual eggs in the coop:
1

Instructions

Your task is to count the number of 1 bits in the binary representation of a number.

Restrictions

Keep your hands off that bit-count functionality provided by your standard library! Solve this one yourself using other basic tools instead.

Bitwise operators

In PHP there are bitwise operators.

For example, the "bitwise and" operator (&) can be used to check that a bit of a number is defined:

$number = 89; // 0b01011001
$mask16 = 16; // 0b00010000
$mask32 = 32; // 0b00100000

$isMask16 = ($number & $mask16) > 0; // 0b00010000 > 0 => TRUE
$isMask32 = ($number & $mask32) > 0; // 0b00000000 > 0 => FALSE
Edit via GitHub The link opens in a new window or tab
PHP Exercism

Ready to start Eliud's Eggs?

Sign up to Exercism to learn and master PHP with 11 concepts, 110 exercises, and real human mentoring, all for free.