> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# IP to CIDR Python Solution with Tests

> Tested Python solution for LeetCode 751 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 751, [Medium](/catalog/medium). Topics: [String](/catalog/topics/string), [Bit Manipulation](/catalog/topics/bit-manipulation). [View on LeetCode](https://leetcode.com/problems/ip-to-cidr/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 751   # by problem number
lcpy gen -s ip_to_cidr   # by problem name
```

## Problem

An IP address is a formatted 32-bit unsigned integer where each group of 8 bits is printed as a decimal number and the dot character `'.'` splits the groups.

* For example, the binary number `00001111 10001000 11111111 01101011` (spaces added for clarity) formatted as an IP address would be `"15.136.255.107"`.

A CIDR block is a format used to denote a specific set of IP addresses. It is a string consisting of a base IP address, followed by a slash, followed by a prefix length `k`. The addresses it covers are all the IPs whose first `k` bits are the same as the base IP address.

* For example, `"123.45.67.89/20"` is a CIDR block with a prefix length of 20. Any IP address whose binary representation matches `01111011 00101101 0100xxxx xxxxxxxx`, where x can be either 0 or 1, is in the set covered by the CIDR block.

You are given a start IP address `ip` and the number of IP addresses we need to cover `n`. Your goal is to use as few CIDR blocks as possible to cover all the IP addresses in the inclusive range `[ip, ip + n - 1]` exactly. No other IP addresses outside of the range should be covered.

Return the shortest list of CIDR blocks that covers the range of IP addresses. If there are multiple answers, return any of them.

### Examples

```
Input: ip = "255.0.0.7", n = 10
Output: ["255.0.0.7/32","255.0.0.8/29","255.0.0.16/32"]
Explanation: The CIDR block "255.0.0.7/32" covers the first address, "255.0.0.8/29" covers the middle 8 addresses, and "255.0.0.16/32" covers the last address.
```

```
Input: ip = "117.145.102.62", n = 8
Output: ["117.145.102.62/31","117.145.102.64/30","117.145.102.68/31"]
```

### Constraints

* 7 \<= ip.length \<= 15
* ip is a valid IPv4 on the form "a.b.c.d" where a, b, c, and d are integers in the range \[0, 255].
* 1 \<= n \<= 1000
* Every implied address ip + x (for x \< n) will be a valid IPv4 address.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/ip_to_cidr/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/ip_to_cidr/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n) for the range length
    # Space: O(1) excluding the output
    def ip_to_cidr(self, ip: str, n: int) -> list[str]:
        def int_to_ip(x: int) -> str:
            return f"{(x >> 24) & 255}.{(x >> 16) & 255}.{(x >> 8) & 255}.{x & 255}"

        a, b, c, d = (int(part) for part in ip.split("."))
        start = (a << 24) | (b << 16) | (c << 8) | d
        ans: list[str] = []
        while n > 0:
            low = start & -start
            max_block = low if start else 1 << 32
            block = 1
            while block * 2 <= max_block and block * 2 <= n:
                block *= 2
            ans.append(f"{int_to_ip(start)}/{32 - block.bit_length() + 1}")
            start += block
            n -= block
        return ans
```

## Complexity

| Time | Space |
| - | - |
| O(n) for the range length | O(1) excluding the output |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.