您的位置:首页 > 编程语言 > Java开发

IP的计算_hdu_2206(郁闷).java

2013-10-12 17:19 483 查看


IP的计算

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 6781    Accepted Submission(s): 1293


Problem Description

在网络课程上,我学到了很多有关IP的知识。IP全称叫网际协议,有时我们又用IP来指代我们的IP网络地址,现在IPV4下用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此不需要用正号出现),如192.168.100.16,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。

但是粗心的我,常常将IP地址写错,现在需要你用程序来判断。

 

Input

输入有多个case,每个case有一行,不超过100个字符。

 

Output

对于每个case,判断输入的IP是否正确,如果正确输入YES,否则NO。

 

Sample Input

192.168.100.16

 

Sample Output

YES

 

import java.io.*;
import java.util.*;

public class Main//很让人蛋疼的题
{
static int INF_INT = 0x3f3f3f3f;
static long INF_LONG = 0x7fffffffffffffffL;
static double PI = Math.acos(-1.0);
static double oo = 10e9;
static double eps = 10e-9;

static Scanner cin = new Scanner(new BufferedInputStream(System.in));

static String str = new String("");
static boolean isvalid()
{
//总长度不能大于15
if (str.length() > 15)
{
return false;
}
int ncnt = 0;
for (int i = 0; i < str.length(); ++i)
{
if ('.' == str.charAt(i))
{
++ncnt;
}
else if (!('0' <= str.charAt(i) && str.charAt(i) <= '9'))
{
return false;
}
}
//只能有3个点
if (ncnt != 3)
{
return false;
}
//开头和结尾不能是.
if ('.' == str.charAt(0) || '.' == str.charAt(str.length() - 1))
{
return false;
}
//两个点不能连着
for (int i = 1; i < str.length(); ++i)
{
if ('.' == str.charAt(i - 1) && '.' == str.charAt(i))
{
return false;
}
}
int ptr = 0;
while (ptr < str.length())
{
int buf = 0;
while (ptr < str.length())
{
if (str.charAt(ptr) == '.')
{
break ;
}
buf *= 10;
buf += (int)(str.charAt(ptr) - '0');
if (buf > 255)
{
return false;
}
++ptr;
}
if (ptr == str.length())
{
break ;
}
if (str.charAt(ptr) == '.')
{
++ptr;
}
}
return true;
}
public static void main(String[] args)
{
while (cin.hasNext())
{
str = cin.nextLine();
System.out.print(isvalid() ? "YES" : "NO");
System.out.println();
}
return ;
}
}

/*import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {//WA
public static void main(String[] args) {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String str=null;
try {
while((str=bf.readLine())!=null){
boolean ok=false;
for(int i=0;i<str.length();i++){
if(!(str.charAt(i)>='0'&&str.charAt(i)<='9'||str.charAt(i)=='.')){
ok=true;
break;
}
}
String s[]=str.split("\\.");
if(s.length!=4||ok){
System.out.println("NO");
continue;
}

for(int i=0;i<4;i++){
if(!(s[i].length()>=1&&s[i].length()<=3)){
ok=true;
break;
}
int a=Integer.parseInt(s[i]);
if(!(a>=1&&a<=255)){
ok=true;
break;
}
}
if(ok)
System.out.println("NO");
else
System.out.println("YES");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu