Published on

leetcode-751 IP to CIDR

Authors
  • avatar
    Name
    Gene Zhang
    Twitter

[751] IP to CIDR

Key Concept: Bit Manipulation for IP Ranges - Convert IP ranges to CIDR blocks by finding the largest power-of-2 block that fits starting from the given IP.

# Given a start IP address and the number of IPs we need to cover,
# return a representation of the range as a list of CIDR blocks.

class Solution:
    def ipToCIDR(self, ip: str, n: int) -> List[str]:
        def ip_to_int(ip):
            parts = list(map(int, ip.split('.')))
            return sum(part << (8 * (3 - i)) for i, part in enumerate(parts))

        def int_to_ip(num):
            return '.'.join(str((num >> (8 * (3 - i))) & 255) for i in range(4))

        start = ip_to_int(ip)
        result = []

        while n > 0:
            # Find rightmost set bit (largest power of 2 that divides start)
            trailing_zeros = (start & -start).bit_length() - 1
            # Find largest block size that doesn't exceed n
            max_size = min(1 << trailing_zeros, n.bit_length() - 1)
            block_size = 1 << max_size

            result.append(f"{int_to_ip(start)}/{32 - max_size}")
            start += block_size
            n -= block_size

        return result

# Time: O(log n), Space: O(1)
# AirBnB: Tests bit manipulation and IP address understanding