Codewars征战记录-JAVA篇(二)

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


本渣渣的方案,splite,然后求值
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
public class CountIPAddresses {

  public static long ipsBetween(String start, String end) {
    return getNum(end)- getNum(start);
  }
  
  public static long getNum(String string) {
    String[] strings = string.split("\\.");
    AtomicLong sum = new AtomicLong();
    IntStream.range(0,strings.length).forEach(i->{
      Integer is = Integer.valueOf(strings[i]);
      sum.addAndGet((long)(is * Math.pow(256,strings.length-i-1)));
      
    });
    return sum.get();
      
  }
}


大佬的解决方案,把乘方放到循环中算,比如最开始的一位会算4次256即256的4次方。
public class CountIPAddresses {

  public static long ipsBetween(String start, String end) {
    return convertToLong(end) - convertToLong(start);
  }
  
  private static long convertToLong(String ip) {
    long res = 0;
    for (String s : ip.split("[.]") )
      res = res * 256 + Long.parseLong(s);
    return res;
  }
}

  

posted on 2020-12-09 16:32  Mrlw  阅读(123)  评论(0编辑  收藏  举报

导航