题解 | #写一段程序判断IP字符串是否属于内网IP#
写一段程序判断IP字符串是否属于内网IP
http://www.nowcoder.com/practice/80ce674313ff43af9d7ac7a41ae21527
import java.util.Scanner;
/**
* @program: Leetcode
* @Author: X.Q.X
* @Date: 2021-08-04 11:36
*/
public class Main {
/**
* 思路:ip转换为整数,判断数字是否属于内网地址对应的数字:
* 10.0.0.0 - 10.255.255.255: 需要判断:10
* 127.0.0.0 - 127.255.255.255 需要判断:127
* 172.16.0.0 - 172.31.255.255 需要判断:17216 和 17231
* 192.168.0.0 - 192.168.255.255 需要判断:192168
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] str = s.split("\\.");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
if(a == 10 || a == 127 || (a == 172 && (b >= 16 && b < 32)) || (a == 192 && b == 168)) {
System.out.println(1);
} else {
System.out.println(0);
}
}
}
查看12道真题和解析