File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments