-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0751-IPToCIDR.cs
63 lines (54 loc) · 1.65 KB
/
0751-IPToCIDR.cs
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//-----------------------------------------------------------------------------
// Runtime: 244ms
// Memory Usage: 32.7 MB
// Link: https://leetcode.com/submissions/detail/335614493/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _0751_IPToCIDR
{
public IList<string> IpToCIDR(string ip, int n)
{
var answer = new List<string>();
long start = IPToLong(ip);
while (n > 0)
{
int mask = Math.Max(33 - BitLength(LowestOneBit(start)),
33 - BitLength(n));
answer.Add(LongToIP(start) + "/" + mask);
start += 1 << (32 - mask);
n -= 1 << (32 - mask);
}
return answer;
}
private long IPToLong(string ip)
{
long answer = 0;
foreach (var x in ip.Split('.'))
answer = 256 * answer + int.Parse(x);
return answer;
}
private int LowestOneBit(long num)
{
var str = Convert.ToString(num, 2);
return (int)Math.Pow(2, str.Length - str.LastIndexOf('1') - 1);
}
private string LongToIP(long x)
{
return $"{x >> 24}.{(x >> 16) % 256}.{(x >> 8) % 256}.{x % 256}";
}
private int BitLength(long x)
{
if (x == 0) return 1;
int count = 0;
while (x > 0)
{
x >>= 1;
count++;
}
return count;
}
}
}