← 返回 openai 的题目列表IP address to CIDR blocks (iterative/range-based)
类型:online_judge
Problem: IP range handling and CIDR representation (multi-part)
Given an IPv4-related input, solve the following incremental subproblems (each part can build on the previous one).
Note: IPv4 uses dotted-decimal notation a.b.c.d, each octet in [0,255].
Part 1: Convert IPv4 string <-> integer
Implement:
ip_to_int(ip: str) -> int: convert an IPv4 string to a 32-bit unsigned integer.
int_to_ip(x: int) -> str: convert a 32-bit unsigned integer back to an IPv4 string.
Constraints
ip is guaranteed to be a valid IPv4 address.
x is in [0, 2^32-1].
Examples
ip_to_int("0.0.0.1") = 1
int_to_ip(1) = "0.0.0.1"
Part 2: Enumerate (or iterate through) an IPv4 range
Given an IPv4 range [start_ip, end_ip] (both valid, start_ip <= end_ip), iterate addresses in increasing order.
Provide:
an interface/logic (return a list or implement an iterator), and discuss complexity.
Constraints
IPv4 only.
end_ip - start_ip can be large; discuss complexity and streaming iteration.
Example
Input: start_ip="0.0.0.1", end_ip="0.0.0.3"
Output sequence: ["0.0.0.1","0.0.0.2","0.0.0.3"]
Part 3: Convert a consecutive IP range to the minimum set of CIDR blocks (core)
Given a consecutive IP range starting at start_ip with length n, output a list of CIDR blocks that exactly cover the range using the minimum number of CIDR blocks.
Use the classic input form:
Input:
start_ip: str
n: int number of consecutive IPs starting from start_ip
Output:
List[str], each like "a.b.c.d/p"
Requirements
The CIDR blocks must:
cover exactly the n consecutive IPs starting at start_ip
use the minimum number of blocks
be output in any order (or in increasing order if requested)
Scale
1 <= n <= 2^32
Test cases (5)
start_ip=0.0.0.0, n=1 -> ["0.0.0.0/32"]
start_ip=0.0.0.0, n=256 -> ["0.0.0.0/24"]
start_ip=0.0.0.1, n=2 -> ["0.0.0.1/32","0.0.0.2/32"]
start_ip=255.255.255.255, n=1 -> ["255.255.255.255/32"]
start_ip=10.0.0.0, n=1024 -> ["10.0.0.0/22"]
Example
Input
0.0.0.0 1
Output
0.0.0.0/32