Problem · Bit Manipulation

IP Address to CIDR Blocks

MediumOpenAIFULLTIMEPHONE SCREEN

Given a starting IPv4 address startIp and a positive integer count, return the minimum set of CIDR blocks that exactly covers the count consecutive IPv4 addresses starting at startIp.

Each CIDR block must be written in the form a.b.c.d/prefix. The returned blocks must cover the range exactly and use the minimum possible number of blocks.

You may assume the input is a valid IPv4 address and that the range stays within the IPv4 space.

Function Description

Complete the function ipRangeToCidrBlocks in the editor below.

ipRangeToCidrBlocks has the following parameters:

  1. String startIp: the first IPv4 address in the range
  2. long count: the number of consecutive IPv4 addresses to cover

Returns

String[]: the minimum CIDR cover for the range.

Examples
01 · Example 1
startIp = "0.0.0.0"
count = 1
return = ["0.0.0.0/32"]

A single IPv4 address is represented by a /32 CIDR block.

02 · Example 2
startIp = "0.0.0.0"
count = 256
return = ["0.0.0.0/24"]

The range from 0.0.0.0 through 0.0.0.255 is exactly one /24 block.

Constraints
  • 1 <= count <= 2^32
  • startIp is a valid IPv4 address.
  • The answer must cover exactly the requested range using the minimum number of blocks.
More OpenAI problems
drafts saved locally
public String[] ipRangeToCidrBlocks(String startIp, long count) {
    // write your code here
}
startIp"0.0.0.0"
count1
expected["0.0.0.0/32"]
sign in to submit