Trains the technique from
LeetCode 751IP to CIDRThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
An allocation covers a run of n addresses. The run starts at the IPv4 address ip, written as four decimal pieces separated by dots, and carries on through the next n - 1 addresses in numeric order. An IPv4 address is read as a 32-bit number, the first piece supplying the highest eight bits.
A block is written as an address followed by a slash and a length, for example "10.0.0.8/29". A block written with length p stands for the 2^(32 - p) addresses that agree with the written address in their top p bits, and the written address must have all of its lowest 32 - p bits clear, so the written address is the first address of the block. The length satisfies 1 <= p <= 32.
Cover the run with blocks, working from its first address to its last. At each step, look at the first address not covered yet and pick the block that starts exactly there, stays inside the run, and holds as many addresses as those two conditions allow. Return the blocks in the order they were picked. Every block must lie inside the run, and together they must cover the run exactly.
Example 1
The first address ends in 6, so a block starting there can hold at most two addresses; `"10.0.0.6/31"` covers 10.0.0.6 and 10.0.0.7. Four addresses are left and the next uncovered address ends in 8, so `"10.0.0.8/30"` covers 10.0.0.8 through 10.0.0.11 and finishes the run.
Example 2
A single block of eight addresses starts at 10.0.0.0 and ends at 10.0.0.7, and eight addresses means a length of 29 because 32 - 29 = 3 and two to the third power is eight.
Example 3
Only one address has to be covered, and a length of 32 stands for a single address.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def ip_to_c_i_d_r(ip: str, n: int) -> list[str]:public List<String> ipToCIDR(String ip, int n)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.