← 返回 openai 的题目列表IP Address Iterator (Forward / Backward / CIDR)
类型:online_judge
Problem: Implement an IP Iterator (Forward / Backward / CIDR)
Implement an iterator that enumerates IPv4 addresses represented as dotted-decimal strings such as "192.168.0.1".
Part 1 (Forward)
Given a start IP start and an end IP end (both inclusive), iterate all IPs in increasing order.
Required API:
has_next() -> bool: whether there is a next IP
next() -> str: returns the next IP string
Part 2 (Backward)
Extend the iterator to support iterating in decreasing order from end down to start (inclusive).
Part 3 (Forward & Backward with CIDR)
Extend the iterator to accept a CIDR block string such as "10.0.0.0/30".
The iterator must be able to:
iterate forward over all IPs covered by the CIDR block
iterate backward over all IPs covered by the CIDR block
You may choose the constructor and method signatures, but you must state them clearly.
Part 4 (Optimization)
Discuss and improve time/space complexity:
State the time complexity of next() / has_next()
State the extra space complexity
Target: do not pre-generate and store the full list of IPs.
Constraints
IPv4 only.
start and end are valid and start <= end numerically.
CIDR prefix length: 0 <= prefix <= 32.
Must handle boundaries like 0.0.0.0 and 255.255.255.255.
Sample Tests
Forward range
input:
start = 192.168.0.1
end = 192.168.0.3
output:
192.168.0.1, 192.168.0.2, 192.168.0.3
Backward range
input:
start = 192.168.0.1
end = 192.168.0.3
output:
192.168.0.3, 192.168.0.2, 192.168.0.1
CIDR forward
input:
cidr = 10.0.0.0/30
output:
10.0.0.0, 10.0.0.1, 10.0.0.2, 10.0.0.3
CIDR backward
input:
cidr = 10.0.0.0/30
output:
10.0.0.3, 10.0.0.2, 10.0.0.1, 10.0.0.0
Boundary single element
input:
start = 255.255.255.255
end = 255.255.255.255
output:
255.255.255.255
Example
Input
RANGE FWD
192.168.0.1 192.168.0.3
Output
192.168.0.1
192.168.0.2
192.168.0.3