-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathip-to-cidr.py
36 lines (31 loc) · 849 Bytes
/
ip-to-cidr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# V0
# V1
# https://zhuanlan.zhihu.com/p/35541808
# DEV
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def ipToCIDR(self, ip, n):
"""
:type ip: str
:type n: int
:rtype: List[str]
"""
def ipToInt(ip):
result = 0
for i in ip.split('.'):
result = 256 * result + int(i)
return result
def intToIP(n):
return ".".join(str((n >> i) % 256) \
for i in (24, 16, 8, 0))
start = ipToInt(ip)
result = []
while n:
mask = max(33-(start & ~(start-1)).bit_length(), \
33-n.bit_length())
result.append(intToIP(start) + '/' + str(mask))
start += 1 << (32-mask)
n -= 1 << (32-mask)
return result