Problem · String

Convert an IPv4 Range to Minimal CIDR Blocks

Learn this problem
MediumOpenAIFULLTIMEONSITE INTERVIEW

Problem statement

You are given a starting IPv4 address ip and a number of consecutive addresses n to cover. Return CIDR blocks that represent exactly this address range.

A CIDR block consists of an IPv4 address, a slash, and the number of fixed leading bits. For example, 192.168.0.0/20 fixes the first 20 bits of each represented address.

Treat each IPv4 address as a 32-bit unsigned integer. Return the smallest possible number of CIDR blocks, ordered from the beginning of the requested range to its end.

Function

ipToCIDR(ip: String, n: int) → String[]

Examples

Example 1

ip = "255.0.0.7"n = 10return = ["255.0.0.7/32", "255.0.0.8/29", "255.0.0.16/32"]

The first address is unaligned and forms a one-address block. The next eight addresses form 255.0.0.8/29, and the final address forms another one-address block.

More OpenAI problems

drafts saved locally
public String[] ipToCIDR(String ip, int n) {
  // write your code here
}
ip"255.0.0.7"
n10
expected["255.0.0.7/32", "255.0.0.8/29", "255.0.0.16/32"]
checking account