首页 > 试题广场 >

IP地址

[编程题]IP地址
  • 热度指数:17778 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
输入一个ip地址串,判断是否合法。

输入描述:
每行有一个IP地址,IP地址的形式为a.b.c.d,其中a、b、c、d都是整数。


输出描述:
可能有多组测试数据,对于每组数据,如果IP地址合法则输出"Yes!”,否则输出"No!”。

合法的IP地址为:
a、b、c、d都是0-255的整数。
示例1

输入

255.255.255.255
512.12.2.3

输出

Yes!
No!

情况自己可以多考虑一些

package com.speical.first;

import java.util.Scanner;
/**
 * ip合理检测
 * 
 * 1.范围正确
 * 2.不能有数字和'.'以外的字符
 * 3.段数为4
 * @author Special
 * @time 2018/02/08 16:08:05
 */
public class Pro203 {

    private static boolean isNum(char ch) {
        return ch >= '0' && ch <= '9';
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        while(input.hasNext()) {
            String str = input.next();
            int num = 0, count = 0;
            boolean flag = true;
            for(int i = 0; i < str.length(); i++) {
                char ch = str.charAt(i);
                if(isNum(ch)) {
                    num = 0;
                    while(i < str.length() && isNum(str.charAt(i))) {
                        num = num * 10 + str.charAt(i++) - '0';
                    }
                    if(i < str.length() && str.charAt(i) != '.' 
                            ||num < 0 || num >= 256) {
                        flag = false;
                        break;
                    }
                    count++;
                }else if(ch != '.') {
                    flag = false;
                    break;
                }
            }
            if(count < 4) { flag = false; }
            System.out.println(flag ? "Yes!" : "No!");
        }
    }

}
发表于 2018-02-08 16:20:20 回复(0)
居然是split(“\\.”);
发表于 2017-05-03 22:02:35 回复(0)
print("Yes!" if [int(item)>=0 and int(item)<=255 for item in input().split('.')].count(True)==4 else "No!")

发表于 2021-01-31 11:14:58 回复(0)
正则表达式来一波~
#include<iostream>
(720)#include<string>
#include<algorithm>
(831)#include<regex>
using namespace std;
int main()
{    
	string s;
	while (getline(cin,s))
	{ 
		int count = 0;
		for (int i = 0; i < s.size(); i++)
			if (s[i] > '9' || s[i] < '0')  count++;
		if (count != 3) cout << "No!"<< endl;
		else
		{
			int flag = 0;
			regex pattern("\\d+");
			smatch result;
			string::const_iterator str = s.begin();
			string::const_iterator str_end = s.end();
			while (regex_search(str, str_end,result, pattern))
			{
				string z=result[0];
				int a = atoi(z.c_str());
				if (a > 255)
				{
					cout << "No!" << endl;
					flag = 1;
					break;
				}
				str = result[0].second;
			}
			if (flag == 0) cout << "Yes!" << endl;
			
		}
	}

}


发表于 2020-03-18 19:14:47 回复(2)
Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        next:
        while (scanner.hasNext()) {
            String s = scanner.nextLine();
            String[] ss = s.split("\\.");
            if (ss.length != 4) {
                System.out.println("No!");
                break next;
            } else {
                for (String s1 : ss) {
                    int i1 = Integer.parseInt(s1);
                    if (!(i1 <= 255 && i1 >= 0)) {
                        System.out.println("No!");
                        break next;
                    }
                }
                System.out.println("Yes");
            }
        }
    }
}


发表于 2020-03-18 16:33:52 回复(0)
#include<bits/stdc++.h>
int main(){
    int a,b,c,d;
    while(scanf("%3d.%3d.%3d.%3d",&a,&b,&c,&d)!=EOF)
        if(a>=0&&a<=255&&b>=0&&b<=255&&c>=0&&c<=255&&d>=0&&d<=255)
            printf("Yes!\n");
        else printf("No!\n");
}
发表于 2019-03-28 22:00:02 回复(0)
import java.util.Scanner;
import java.util.regex.Pattern;
 
public class Main{
    public static void main(String args[]){
            Scanner sc = new Scanner(System.in);
            String content = sc.next();
        //java中的"\"要+1
            String pattern = "(((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|" +
                    "(25[0-5]))\\.){3}" +
                    "((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))";

            boolean isMatch = Pattern.matches(pattern, content);
            if(isMatch){
                System.out.println("Yes!");
            }else {
                System.out.println("No!");
            }
        }
}

发表于 2018-09-23 15:42:28 回复(2)
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner scanr=new Scanner(System.in);
        String str=scanr.nextLine();
        if (str.split("\\.").length!=4)
            System.out.println("No!");
        else {
            for (int i = 0; i < 4; i++) {
                int value = Integer.parseInt(str.split("\\.")[i]);
                if (value < 0 || value > 255) {
                    System.out.println("No!");
                    return;
                }
            }   System.out.println("Yes!");
        }
    }
} 

#include<stdio.h>

int main(){
    char s[100];
    gets(s);
    int i=0;
    int v=0;
    int c=0;
    while(s[i]!='\0'){
        if(s[i]=='.')
            c++;
        i++;
    }
    if(i>15 || c!=3){
        printf("No!");
        return 0;
    }
    s[i]='.';
    s[i+1]='\0';
    i=0;
    while(s[i]!='\0'){
        while(s[i]!='.'){
            v=v*10+(s[i]-'0');
            i++;
        }
        if(v<0 || v>255){
            printf("No!");
            return 0;
        }
        v=0;
        i++;
    }
    printf("Yes!");
    return 0;
}

编辑于 2018-06-01 11:20:56 回复(0)
测试用例:
298.67.24.168

对应输出应该为:

Yes!

你的输出为:

No!
。。。。。。

发表于 2017-09-13 16:56:14 回复(1)
#include <cstdio>

int main()
{
	int ip[4];
	int n;
	while (scanf("%d", &n) != EOF)
	{
		for (int i = 0; i < n; i++)
		{
			scanf("%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]);
			bool flag = true;
			for (int j = 0; j < 4; j++)
			{
				if (ip[j] < 0 || ip[j] > 255)
				{
					flag = false;
					break;
				}
			}
			if (flag)
				printf("Yes!\n");
			else
				printf("No!\n");
		}
	}
	return 0;
}

发表于 2017-06-04 18:44:13 回复(1)
<?php
$char = fgets(STDIN);
$result = array();
$i=0;
while($i<$char){
    fscanf(STDIN,"%d.%d.%d.%d",$a,$b,$c,$d);
    if($a<0||$b<0||$c<0||$d<0||$a>255||$b>255||$c>255||$d>255){
        $result[$i]="No!";
    }else{
        $result[$i]="Yes!";
    }
    $i++;
}
echo implode("\n",$result);


编辑于 2017-04-09 22:16:13 回复(0)
/* 其实我这种做法挺笨的。先找出'.'所在的下标和数量,不符合的返回;然后将字符转化成数字,与255比较大小,不符合的返回;最后还比较了第四个数字,麻里麻烦的,而且TMD万一输入是负数?很尴尬的题 */
#include <stdio.h>
#include <string.h>
bool checkIP(char *s)
{
	int numOfChar = strlen(s);
	if(numOfChar>15)					// IP v4  0.0.0.0 ~ 255.255.255.255
		return false;
	int i,dotAdd[3],dotCount = 0;
	for (i = 0; i < numOfChar; i++)		// 找出.所在的下标		可以考虑边判断边动指针i
	{
		if (s[i] == '.')
		{
			dotCount++;	
			if (dotCount > 3)
				return false;
			dotAdd[dotCount-1] = i;		// 日常下标减一  常见错误
		}
	}
	if (dotCount != 3)
		return false;
	int num, j;
	for (i = 0; i < dotCount; i++)		// 只判断了.前面的符不符合要求,最后一个数字也要判断
	{
		num = 0,j = 1;					// 通过.的位置定位其前后的数字字符并转化为数字
		int index = dotAdd[i]-1;		// 定位字符串中的.对其前面的数进行转换和求和操作  index > 0 && s[index] != '.'
		while (index >= 0 && s[index] != '.')
		{
			num = num + j*(s[index] - '0');
			j *= 10;
			index--;
		}
		if (num > 255)
			return false;
	}
	
	int lastDot = dotAdd[2];
	num = 0, j = 1;
	while (s[numOfChar - 1] != '.')
	{
		numOfChar--;
		num = num + j*(s[numOfChar] - '0');
		j *= 10;
	}
	if (num > 255)
		return false;
	return true;
}

int main()
{
	char input[20];
	int n;
	scanf("%d", &n);
	while (n--)
	{
		scanf("%s", input);
		bool a = checkIP(input);
		(a == false) ? printf("No!\n") : printf("Yes!\n");
	}
	return 0;
}
/*下面是另外一种思路*/
bool checkIP(char *s)
{
	int index = strlen(s) - 1;
	if (strlen(s) > 15)							// 0.0.0.0 ~ 255.255.255.255
		return false;
	int i,dotCount = 0;

	for (i = 0; i <= index; i++)			// 判断是否存在非法输入
	{
		if (s[i] == '.')
		{
			dotCount++;
			continue;
		}
		else if (s[i] >= '0' && s[i] <= '9')
			continue;
		else
			return false;
	}
	if (dotCount != 3)						// 合格的ip v4 地址有三个点
		return false;

	// 使指针首先指向字符串的最后一个字符,从后往前扫是为了方便计算
	while (1)
	{
		int num = 0, j = 1;
		while (s[index] != '.' && index >= 0)
		{
			num = num + (s[index] - '0') * j;
			j *= 10;
			index--;
		}
		index--;
		if (num > 255)
			return false;
		if (index < 0)
			break;
	}
	return true;
}

int main()
{
	char input[20];
	int n;
	scanf("%d", &n);
	while (n--)
	{
		scanf("%s", input);
		bool a = checkIP(input);
		(a == false) ? printf("No!\n") : printf("Yes!\n");
	}
	return 0;
}

编辑于 2016-12-25 22:19:19 回复(0)
#include <stdio.h>
int main(){
    int n, a, b, c, d;
    scanf("%d", &n);
    while(n--){
    	scanf("%d.%d.%d.%d", &a, &b, &c, &d);
        if (a < 0 || b < 0 || c < 0 || d < 0 || a > 255 || b > 255 || c > 255 || d > 255)
            printf("No!\n");
        else
            printf("Yes!\n");
    }
    return 0;
}

编辑于 2017-04-11 20:09:38 回复(19)
#include<stdio.h>
#include<string.h>
int main(){
    char a[20];
    int i=0;
    gets(a);
    int sign=1;
    for(i=0;i<strlen(a);i++){
        int sum=0;
        while(a[i]!='.'&&a[i]!='\0'){
            sum=10*sum+a[i]-'0';
            i++;
        }
        if(sum<0||sum>255){
            sign=0;
            break;
        }
    }
    if(sign==1)
        printf("Yes!");
    else
        printf("No!");
    return 0;
}

发表于 2018-03-19 15:37:40 回复(2)

python三行代码搞定。

while True:
    try:
        a = int(input())
        for i in range(a):
            print("Yes!" if sum(map(lambda c: 0 <= c <= 255, map(int, input().split(".")))) == 4 else "No!")

    except:
        break
发表于 2017-10-04 08:54:12 回复(7)
//代码独立开来;
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<stack>
using namespace std;
int strToInt(string str,int begin,int end)
{
	int num=0;
	for(int i=begin;i<end;i++)
	{
		num=num*10+(str[i]-'0');
	}
	return num;
}

bool Comp(int number)
{
	return (number>=0 && number<=255);
}
bool isIpaddress(string str)
{
	int x1=str.find('.',0);
	int x2=str.find('.',x1+1);
	int x3=str.find('.',x2+1);
	//cout<<x1<<" "<<x2<<" "<<x3<<endl;
	
	int y1=strToInt(str,0,x1);
	int y2=strToInt(str,x1+1,x2);
	int y3=strToInt(str,x2+1,x3);
	int y4=strToInt(str,x3+1,str.length());
	
	//cout<<y1<<" "<<y2<<" "<<y3<<" "<<y4<<endl;
	if(Comp(y1)&&Comp(y2)&&Comp(y3)&&Comp(y4))
	    return true;
	else
	    return false;
	    
}
int main()
{
	int N;
	string str;
	while(cin>>N)
	{
		for(int i=1;i<=N;i++)
		{
			cin>>str;
			if(isIpaddress(str))
		   		cout<<"Yes!"<<endl;
	    	else
	        	cout<<"No!"<<endl;
	    }
	}
	return 0;
} 

发表于 2016-08-14 20:56:12 回复(0)

防止出现255.255.255.255.255类似的错误

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int a,b,c,d;
    string tmp;
    scanf("%d.%d.%d.%d",&a,&b,&c,&d);
    getline(cin,tmp);
    if(a>=0&&a<=255 && b>=0&&b<=255 && c>=0&&c<=255 && d>=0&&d<=255 && tmp.empty())
    {
        printf("Yes!\n");
    }
    else
        printf("No!\n");
    return 0;
} 
发表于 2019-05-14 10:05:12 回复(0)

#include <iostream>

using namespace std;

int main() {//合法ip地址
     char dot;
     int a,b,c,d;
     while(cin>>a>>dot>>b>>dot>>c>>dot>>d){//不考虑点
        if(a>=0&&a<=255&&b>=0&&b<=255&&c>=0&&c<=255&&d>=0&&d<=255){
            cout<<"Yes!"<<endl;
        }else{
            cout<<"No!"<<endl;
        }
     }
}



发表于 2023-01-19 14:31:02 回复(0)
#include <iostream>
using namespace std;
int main(){
    int n, a, b, c, d;
    char ch;                    //ch字符吸收输入中的'.'
    cin>>n;
    while(n--){
      cin>>a>>ch>>b>>ch>>c>>ch>>d;
        if (a < 0 || b < 0 || c < 0 || d < 0 || a > 255 || b > 255 || c > 255 || d > 255)
            printf("No!\n");
        else
            printf("Yes!\n");
    }
    return 0;
}

发表于 2020-01-06 21:57:05 回复(0)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
bool isTrue(string& str){
    int num = 0;
    for(char s : str){
        if(s != '.'){
            num *= 10;
            num += s - '0';
        }else{
            if(num > 255 || num < 0){
                return false;
            }
            num = 0;
        }
    }
    if(num > 255 || num < 0){
        return false;
    }
    return true;
}
int main(){
    vector<string> ss;
    string t;
    while(cin>>t){
        ss.push_back(t);
        t = "";
    }
    for(int i = 0; i < ss.size(); i++){
        if(isTrue(ss[i])){
            cout<<"Yes!"<<endl;
        }else{
            cout<<"No!"<<endl;
        }
    }
}

发表于 2022-09-08 20:42:03 回复(0)

问题信息

难度:
135条回答 12664浏览

热门推荐

通过挑战的用户

查看代码