Skip to content

Commit 4dd9e34

Browse files
committed
Add a solution to IP to CIDR
1 parent 23f48fb commit 4dd9e34

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Math/IPToCIDR.swift

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
**
2+
* Question Link: https://leetcode.com/problems/ip-to-cidr/
3+
* Primary idea: Bit manipulation. Get the most right 1 and update steps based on it.
4+
*
5+
* Time Complexity: O(mlogn), Space Complexity: O(m)
6+
* m is the length of the ip string
7+
*/
8+
9+
class IPToCIDR {
10+
private let BASE = 256
11+
12+
func ipToCIDR(_ ip: String, _ n: Int) -> [String] {
13+
var currentIPInt = ipToInt(ip)
14+
var res = [String](), n = n
15+
16+
while n > 0 {
17+
// get the most right one bit
18+
var step = currentIPInt & -currentIPInt
19+
20+
if step == 0 {
21+
step = Int(pow(Double(2), Double(32)))
22+
}
23+
24+
while step > n {
25+
step /= 2
26+
}
27+
28+
res.append(IntToIP(currentIPInt, step))
29+
30+
currentIPInt += step
31+
n -= step
32+
}
33+
34+
return res
35+
}
36+
37+
private func ipToInt(_ ip: String) -> Int {
38+
var x = 0
39+
let strings = ip.split(separator: ".")
40+
41+
for str in strings {
42+
x = x * BASE + Int(str)!
43+
}
44+
45+
return x
46+
}
47+
48+
private func IntToIP(_ x: Int, _ step: Int) -> String {
49+
var res = Array(""), x = x
50+
51+
for i in 0..<4 {
52+
res.insert(contentsOf: String(x % BASE), at: 0)
53+
if i != 3 {
54+
res.insert(".", at: 0)
55+
}
56+
x /= BASE
57+
}
58+
59+
var len = 33, step = step
60+
while step > 0 {
61+
len -= 1
62+
step /= 2
63+
}
64+
65+
res += "/\(len)"
66+
67+
return String(res)
68+
}
69+
}

0 commit comments

Comments
 (0)