Balls in a Binary Tree
InterviewTime limit1sMemory limit128 MB
Follow the n-th ball down h levels of toggling switches, going left on odd visits and right on even visits, to find its leaf number.
- Level
Medium5 of 10
- Topics
- Bit manipulation, Simulation, Math
- Solved
- No attempts yet
Problem
You are given a full binary tree of height (see the figure).

Every edge is either open or closed. Initially all left edges are open. Starting from the root, you drop balls one by one. Each ball always travels through the currently open edge; immediately after passing through it, that edge is closed and the sibling edge of the same vertex is opened. In other words, if the left edge was open, the left one is closed and the right one is opened; if the right edge was open, the right one is closed and the left one is opened.
Determine which leaf vertex the -th ball reaches. The bottom vertices are numbered from to , left to right.
Input
The first line contains two integers and (, ): the number of balls dropped and the height of the binary tree, respectively.
Output
Print a single integer: the number of the vertex the -th ball reaches.
Hint
For a tree of height , the balls land in vertices numbered in order, so the 4th ball reaches vertex . When the tree has a single vertex (numbered ), so every ball lands in vertex .