题解 | 判断两个IP是否属于同一子网
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
IpMask mask = new IpMask(in.nextLine());
IpMask ip1 = new IpMask(in.nextLine());
IpMask ip2 = new IpMask(in.nextLine());
if(!mask.maskIsValid() || !ip1.ipIsValid() || !ip2.ipIsValid()){
System.out.println(Result.INVALID);
continue;
}
long maskt = mask.getLong();
long ipt1 = ip1.getLong();
long ipt2 = ip2.getLong();
if((maskt&ipt1) == (maskt&ipt2)){
System.out.println(Result.SAME);
}else{
System.out.println(Result.NOT);
}
}
}
// 结果定义
private static class Result{
static int INVALID = 1;
static int SAME = 0;
static int NOT = 2;
}
// IpMask类定义
private static class IpMask{
public int[] a;
public IpMask(String s){
String[] ss = s.split("[.]+");
this.a = new int[ss.length];
for(int i=0; i<this.a.length; i++){
this.a[i] = Integer.valueOf(ss[i]);
}
}
// IP是否合法
public boolean ipIsValid(){
if(this.a==null || this.a.length!=4){
return false;
}
for(int x : this.a){
if(x<0 || x>255){
return false;
}
}
return true;
}
// mask是否合法
public boolean maskIsValid(){
if(!ipIsValid()){
return false;
}
StringBuilder sb = new StringBuilder();
for(int x : this.a){
sb.append(String.format("%8s", Integer.toBinaryString(x))
.replaceAll(" ", "0"));
}
int last1 = sb.lastIndexOf("1");
int fist0 = sb.indexOf("0");
if(fist0==-1){// 全1
return true;
}else if(fist0 < last1){ // 11011
return false;
}else{// 11100
return true;
}
}
// IP地址转换为Long
public long getLong(){
long ans = 0;
for(int x : this.a){
ans = ans*256 + x;
}
return ans;
}
}
}
查看11道真题和解析