Knockout Bracket Check

Easybit manipulationAlso known as Power of Two

You run the sign-up desk for a table tennis club's knockout tournament. In each round, players pair off and the losers go home, so the field halves every round. That only works cleanly if the number of players is 1, 2, 4, 8, 16, and so on. Any other count means someone gets a free pass (a "bye") in some round, and the players hate byes.

The sign-up screen takes whatever number the organiser types, including mistakes like 0 or -4. Before printing a bracket, the screen should say whether the count gives a bracket with no byes at all.

Your task

Write isFullBracket(players). Return true if players is a power of two (1, 2, 4, 8, …), and false otherwise.

0 and every negative number return false. 1 returns true: one player is champion without playing. Try to answer without a loop.

isFullBracket(players: int) → bool

Examples

Example 1
Input
players = 16
Output
true
Why

16 → 8 → 4 → 2 → 1. Every round halves the field evenly, so no byes. In binary, 16 is 10000: a single 1 bit.

Example 2
Input
players = 12
Output
false
Why

12 → 6 → 3, and 3 players cannot pair off. 12 is even, but being even is not enough. In binary, 12 is 1100: two 1 bits.

Example 3
Input
players = 1
Output
true
Why

1 is 2 to the power 0. In binary it is just 1, a single 1 bit.

Constraints

  • -2,147,483,648 ≤ players ≤ 2,147,483,647
Start with brute force

Keep halving: while the number is even, divide it by 2. If you end at exactly 1, it was a power of two. This takes at most about 31 steps, so speed is not really the problem.

The trouble is the edges. With 0, "while even, halve" loops forever, because 0 / 2 is still 0 and still even. Negative numbers need their own care too. The bit trick answers in one step and the only edge to remember is n > 0.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code