Coderwars 6 Kyu : Count IP Addresses

题目

Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).

All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.

Examples
ips_between(“10.0.0.0”, “10.0.0.50”) == 50
ips_between(“10.0.0.0”, “10.0.1.0”) == 256
ips_between(“20.0.0.10”, “20.0.1.0”) == 246

分析

没啥好说的,就是进制转换

代码

using System;
using System.Linq;
using System.Collections.Generic;
public class CountIPAddresses
{
public static long IpsBetween(string start, string end)
{
  long[] starts = start.Split('.').Select(s=>long.Parse(s)).ToArray();
  long[] ends = end.Split('.').Select(s=>long.Parse(s)).ToArray();
  long n1 = 256 * (256 * 256 * starts[0] + 256 * starts[1] + 1 * starts[2]) + starts[3];
  long n2 = 256 * (256 * 256 * ends[0] + 256 * ends[1] + 1 * ends[2]) + ends[3];     
  return n2-n1;
}
}

发表评论

您的电子邮箱地址不会被公开。