LeetCode 751: IP to CIDR Solution
Master LeetCode problem 751 (IP to CIDR), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
751. IP to CIDR
Problem Explanation
Explanation:
Given an IP address and a range, we need to convert the IP address to a CIDR block representation.
The algorithm to solve this problem involves the following steps:
- Convert the IP address to a 32-bit integer.
- Calculate the number of trailing zeros in the IP address to determine the size of the block.
- Iterate through the range, updating the IP address and block size accordingly.
- Convert the IP address and block size back to CIDR notation.
Time complexity: O(N), where N is the number of IP addresses in the range. Space complexity: O(1)
: :
Solution Code
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<String> ipToCIDR(String ip, int n) {
long start = ipToLong(ip);
List<String> res = new ArrayList<>();
while (n > 0) {
int mask = Math.max(33 - bitLength((int) (start & -start)), 33 - bitLength(n));
res.add(longToIP(start) + "/" + mask);
start += 1 << (32 - mask);
n -= 1 << (32 - mask);
}
return res;
}
private long ipToLong(String ip) {
String[] parts = ip.split("\\.");
long res = 0;
for (String part : parts) {
res = res * 256 + Integer.parseInt(part);
}
return res;
}
private String longToIP(long x) {
return String.format("%s.%s.%s.%s", (x >> 24) & 255, (x >> 16) & 255, (x >> 8) & 255, x & 255);
}
private int bitLength(int x) {
if (x == 0) {
return 1;
}
int res = 0;
while (x > 0) {
x >>= 1;
res++;
}
return res;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 751 (IP to CIDR)?
This page provides optimized solutions for LeetCode problem 751 (IP to CIDR) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 751 (IP to CIDR)?
The time complexity for LeetCode 751 (IP to CIDR) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 751 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 751 in Java, C++, or Python.