Skip to content

Commit 1e5baae

Browse files
authored
Create 751-ip-to-cidr.js
1 parent 9796c23 commit 1e5baae

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

751-ip-to-cidr.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {string} ip
3+
* @param {number} n
4+
* @return {string[]}
5+
*/
6+
const ipToCIDR = function (ip, n) {
7+
const ipToLong = (ip) =>
8+
ip.split('.').reduce((acc, x) => 256 * acc + parseInt(x), 0)
9+
const longToIp = (long) =>
10+
[24, 16, 8, 0].map((i) => (long >>> i) % 256).join('.')
11+
const bitLength = (num) => Math.floor(Math.log2(num)) + 1
12+
const ans = []
13+
let long = ipToLong(ip)
14+
while (n) {
15+
let mask = Math.max(33 - bitLength(long & -long), 33 - bitLength(n))
16+
ans.push(longToIp(long) + '/' + mask)
17+
long += 1 << (32 - mask)
18+
n -= 1 << (32 - mask)
19+
}
20+
return ans
21+
}

0 commit comments

Comments
 (0)