Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Using Bit Manipulation. This code handles 0.0.0.0 IP address. 0.0.0.0 is a
- * valid IP address. https://en.wikipedia.org/wiki/IPv4#Special-use_addresses
- *
- * Refer:
- * https://leetcode.com/problems/ip-to-cidr/discuss/110222/Very-Simple-Java-Solution-(beat-100)
- *
- * Time Complexity: O(M + N log N) ~= O(N log N)
- *
- * O(M) = to convert String IP to decimal number. This can be considered
- * constant since the length of IP cannot be less than 4 and more than 15. Code
- * inside the first while loop takes LOG N time. This can be considered constant
- * since there are max 32 bits in an IP address. This while loop will iterate
- * for multiple times till N IP address are generated. Thus time complexity of
- * this while loop is O(N log N).
- *
- * Space Complexity: O(1)
- *
- * M = Length of IP String. N = Number of IPs required.
- */
- class Solution {
- public List<String> ipToCIDR(String ip, int n) {
- List<String> result = new ArrayList();
- if (ip == null || n <= 0) {
- return result;
- }
- if (n == 1) {
- result.add(ip + "/32");
- return result;
- }
- // Converting String IP to its decimal number.
- long ipNum = 0;
- for (String o : ip.split("\\.")) {
- ipNum = ipNum * 256 + Long.parseLong(o);
- }
- while (n > 0) {
- // This will extract the integer corresponding to the first set bit from right.
- // This will help to get the lenght of the CIDR block. Zero bits after this set
- // bit are changed to create next IP addresses.
- long cidrBlockLen = ipNum & -ipNum;
- // This IF condition is required if input IP is 0.0.0.0
- if (cidrBlockLen == 0) {
- cidrBlockLen = n;
- int count = 0;
- while (cidrBlockLen > 0) {
- cidrBlockLen >>= 1;
- count++;
- }
- cidrBlockLen = 1 << (count - 1);
- }
- while (cidrBlockLen > n) {
- cidrBlockLen /= 2;
- }
- result.add(genCidrBlock(ipNum, cidrBlockLen));
- // Getting ready for next iteration.
- ipNum += cidrBlockLen;
- n -= cidrBlockLen;
- }
- return result;
- }
- private String genCidrBlock(long ipNum, long blockLen) {
- // Extracting the octets from the IP address.
- int[] ip = new int[4];
- for (int i = 0; i < 4; i++) {
- ip[i] = (int) ipNum & 255;
- ipNum >>= 8;
- }
- // Calculating the common prefix of CIDT block.
- int prefix = 33;
- while (blockLen > 0) {
- prefix--;
- blockLen /= 2;
- }
- return ip[3] + "." + ip[2] + "." + ip[1] + "." + ip[0] + "/" + prefix;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement