首页 > 试题广场 >

合法IP

[编程题]合法IP
  • 热度指数:286299 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

IPV4地址可以用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此正号不需要出现),如10.137.17.1,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。

现在需要你用程序来判断IP是否合法。

数据范围:数据组数:
进阶:时间复杂度:,空间复杂度:



输入描述:

输入一个ip地址,保证不包含空格



输出描述:

返回判断的结果YES or NO

示例1

输入

255.255.255.1000

输出

NO
while True:
    try:
        # 遍历输入的每个段
        for i in input().strip().split('.'):
            # 如果是数字,并且该数字对应的整型在[0,256]范围内
            if not (i.isdigit() and 0 <= int(i) <= 255):
                print('NO')
                break
        # 如果上面的遍历没有触发break,则执行这个else,打印YES
        else:
            print('YES')
    except:
        break

发表于 2019-11-26 20:06:39 回复(2)
#include<iostream>
#include<string>
using namespace std;
void StringToIp(string s,int ip[4])
{
    s='.'+s;
    int value=0,k=0;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='.')
        {
            ip[k++]=value;
            value=0;
        }
        else
            value=value*10+s[i]-'0';
    }
    
}


bool Feifa1 (string s) //判断是不是只有数字和'.'组成
{
   for(int i=0; i<= s.size()-1;i++) 
   {
       if (!(s[i]=='.' || (s[i]<='9' && s[i]>='0')))
       {
           return false;
           break;
       }
   }
    return true;
}


bool Feifa2 (string s) //判断是存在连续的'.'
{
   for(int i=0; i<= s.size()-2;i++) 
   {
       if (s[i]=='.' && s[i+1]=='.' )
       {
           return false;
           break;
       }
   }
    return true;
}

bool Feifa3 (int ip[4]) //判断在0~255之间
{
    for (int j = 0; j < 4; ++j)
    {
        if (ip[j] < 0 || ip[j]>255)
        {
           return false;
           break;
        }
    }
return true;
}

int main(void)
{
    string s;
    int ip[4];
    while(getline(cin, s))
    {
        StringToIp(s, ip);
        if(Feifa1(s) && Feifa2(s) && Feifa3(ip))
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }
}

发表于 2016-07-18 19:01:39 回复(2)
c++
样例库更新了,因此很多题解不再适用,不过解法还是大同小异的。主要是增加了:
1. 每段地址不能以0开头;
2.可能会含有除了数字外的字符。
只要增加这些功能就行了。
#include <bits/stdc++.h>

using namespace std;

bool judgeIP(string& s){
    if(s.empty()) return false;
    for(char ch : s){
        if(!(ch >= '0' && ch <= '9')) return false;// 不是数字不行
    }
    int n = stoi(s);
    string s2 = to_string(n);
    if(s2.size() != s.size()) return false;
    if(n > 255) return false;
    return true;
}
int main() {
    string str;
    while(cin >> str){
        vector<string> v;
        int start = 0;
        for(int i = 0; i <= str.size(); i ++){
            if(i == str.size() || str[i] == '.'){
                string temp = str.substr(start, i - start);
                start = i + 1;
                v.push_back(temp);
            }
        }
        if(v.size() != 4){
            cout << "NO" << endl;
        }else{
            bool isLegal = true;
            for(string s : v){
                if(judgeIP(s) == false){
                    isLegal = false;
                    break;
                }
            }
            if(isLegal) cout << "YES" << endl;
            else cout << "NO" << endl;
        }
    }
    return 0;
}


发表于 2022-07-12 15:52:49 回复(0)
内置函数yyds
let ip = readline()
let ips = ip.split('.')
console.log(ips.length===4 && ips.every(el=> {
  return parseInt(el).toString() === el && parseInt(el)<=255 && parseInt(el)>=0
})? 'YES' : 'NO')

发表于 2022-05-21 15:40:24 回复(0)
为什么这题目是中等难度
发表于 2022-03-06 18:27:18 回复(0)
while 1:
    try:
        a= input().split('.')
        if len(a)!=4 or '' in a:
            print("NO")
        else:
            for i in a:
                if i.isdigit():
                    if len(i)>1 and i[0]=='0':
                        print("NO")
                        break
                    if 0>int(i) or int(i)>255:
                        print('NO')
                        break
                else:
                    print('NO')
                    break
            else:
                    print("YES")
    except EOFError:break        
发表于 2021-12-03 01:38:21 回复(0)
import java.util.Scanner;

/**
* 练习写个正则表达式
*/
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String s = scanner.nextLine();
            solution(s);
        }
    }

    /**
     * ip地址判断
     * <p>
     * 正则表达式
     * 0-199: (0|1)?[0-9]{1,2}
     * 200-249: 2[1-4][0-9]
     * 250-255: 25[0-5]
     * 0-255: (((0|1)?[0-9]{1,2})|(2[1-4][0-9])|(25[0-5]))
     * ip: ((((0|1)?[0-9]{1,2})|(2[1-4][0-9])|(25[0-5]))\\.){3}(((0|1)?[0-9]{1,2})|(2[1-4][0-9])|(25[0-5]))
     *
     * @param ip
     */
    public static void solution(String ip) {
        boolean matches = ip.matches("((((0|1)?[0-9]{1,2})|(2[1-4][0-9])|(25[0-5]))\\.){3}(((0|1)?[0-9]{1,2})|(2[1-4][0-9])|(25[0-5]))");
        System.out.println(matches ? "YES" : "NO");
    }
}

发表于 2021-08-18 23:58:45 回复(0)
#include <bits/stdc++.h>

using namespace std;

int main(){
    unsigned int a,b,c,d;
    char ch;
    while(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)){
            cout << "NO" << endl;
        } else if((a<0 || a > 255) || (b<0 || b > 255) || (c<0 || c > 255) || (d<0 || d > 255)){
            cout << "NO" << endl;
        } else {
            cout << "YES" << endl;
        }
    }
}

发表于 2021-04-14 14:21:28 回复(0)
将ip地址按点分割为4个数,检查每个数是不是在[0,255]就可以了
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while((line = br.readLine()) != null){
            String[] ip = line.trim().split("\\.");
            boolean flag = true;
            for(int i = 0; i < ip.length; i++){
                int num = Integer.parseInt(ip[i]);
                if(num < 0 || num > 255){
                    flag = false;
                    break;
                }
            }
            if(flag)
                System.out.println("YES");
            else
                System.out.println("NO");
        }
    }
}
python版
while True:
    try:
        for num in list(map(int, input().split('.'))):
            if num < 0&nbs***bsp;num > 255:
                print("NO")
                break
        else:
            print("YES")
    except:
        break

编辑于 2021-03-26 14:03:09 回复(0)
import java.util.Arrays;
import java.util.Scanner;
public class Main {
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String str = scanner.nextLine();
            String[] strs = str.split("\\.");
            boolean flag=true;
            for(String s: strs){
                int num = Integer.parseInt(s);
                if(num<=255 && num>=0){
                    flag = flag;
                }else{
                    flag=false;
                }
            }
            if(flag){
                System.out.println("YES");
            }else{
                System.out.println("NO");
            }
        }
    }
}
发表于 2020-07-11 08:51:23 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main(){
    int a,b,c,d;
    while(4==scanf("%d.%d.%d.%d",&a,&b,&c,&d)){
        if(0<=a&&a<=255&&0<=b&&b<=255&&0<=c&&c<=255&&0<=d&&d<=255) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

发表于 2020-06-21 23:34:47 回复(0)
根据题意只要ip中不包含空格,数字范围合法,且是四个无符号整数以点连接就是正确格式,只要题目上明确说了特殊情况就不用考虑其他情况,因为测试的时候根本不会给你输入那些乱七八糟的格式
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        while (s.hasNextLine()){
            String ip = s.nextLine();
            boolean flag = true;
            if(ip.contains(" "))flag = false;
            else{
                String[] ipPart = ip.split("\\.");
                if(ipPart.length != 4)flag = false;
                else{
                    for(int i = 0;i < ipPart.length;i ++){
                        if(Integer.parseInt(ipPart[i]) > 255 || Integer.parseInt(ipPart[i]) < 0)flag = false;
                    }
                }
            }
            System.out.println(flag?"YES":"NO");
        }
    }
}


发表于 2020-04-26 14:32:55 回复(0)
while True:
    try:
        ls=list(input().split('.'))
        if len(ls)!=4:
            print('NO')
        else:
            x=True
            for i in ls:
                #print(i)
                if int(i)<=255 and int(i)>=0:
                    continue
                else:
                    x=False
            if x:
                print('YES')
            else:
                print('NO')
    except:
        break

发表于 2019-08-20 20:18:50 回复(0)
import java.util.Scanner;
public class Main{     public static void main(String[] args) {         Scanner sc = new Scanner(System.in);         while (sc.hasNext()) {             String string = sc.nextLine();             String[] arrs = string.split("\\.");             String illegal="YES";
          for(int i=0;i<arrs.length;i++)
          {
              if(Integer.parseInt(arrs[i])>255||Integer.parseInt(arrs[i])<0)
              {
                  illegal="NO";
                  break;
              }
          }             System.out.println(illegal);         }     }
}
居然只要判断数字大小就过了
发表于 2019-07-01 20:39:03 回复(0)
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        Scanner jin = new Scanner(System.in);
        while (jin.hasNext()) {
            String s = jin.nextLine();
            boolean flag = true;
            String[] strings = s.split("\\.");
            for (int i = 0; i < strings.length; i++) {
                int num = Integer.valueOf(strings[i]);
                if (!(num >= 0 & num <= 255)) {
                    flag = false;
                }
            }
            if (flag) {
                System.out.println("YES");
            } else {
                System.out.println("NO");
            }
        }
    }
}
发表于 2019-03-16 12:56:20 回复(0)
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
            while(sc.hasNext()){
                String line = sc.nextLine();
                boolean flag = true;
                if(line.contains(" ")) {
                    flag = false;
                } else {
                    String[] ips = line.split("\\.");
                    for(int i=0; i<ips.length; i++) {
                        if(Integer.valueOf(ips[i])<0 || Integer.valueOf(ips[i])>255) {
                            flag = false;
                            break;
                        }
                    }
                }
                if(flag) {
                    System.out.println("YES");
                } else {
                    System.out.println("NO");
                }
            }
    }
}

发表于 2018-10-09 13:28:26 回复(0)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <cctype>
#include <vector>

using namespace std;

int main()
{     int a[4];     char c[3];     while(cin>>a[0]>>c[0]>>a[1]>>c[1]>>a[2]>>c[2]>>a[3])     {         if(c[0]=='.' && c[1]=='.' && c[2]=='.')         {             bool flag = true;             for(int i=0;i<4;i++)                 if(a[i]<0 || a[i]>255)                     flag = false;             if(flag)                 cout<<"YES"<<endl;             else                 cout<<"NO"<<endl;                         }     }     return 0;
}

发表于 2018-07-10 00:07:57 回复(0)

其实情况太多了。。。

package com.special.spet;

import java.util.Scanner;

/** 
*
* @author special
* @date 2017年12月9日 上午9:46:31
*/
public class Pro89 {
    public 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.nextLine();
            String[] ips = str.split("\\.");
            if(ips.length != 4)
                System.out.println("NO");
            else{
                boolean flag = false;
                for(int i = 0; i < ips.length; i++){
                    int temp = 0;
                    int index = 0;
                    while(index < ips[i].length() && isNum(ips[i].charAt(index)))
                        temp = temp * 10 + (ips[i].charAt(index++) - '0');
                    if(index < ips[i].length() || temp > 255){ //若是某个段位出现非数字或者范围超出跳出
                        flag = true;
                        break;
                    }
                }
                if(!flag) System.out.println("YES");
                else      System.out.println("NO");
            }
        }
    }

}
发表于 2017-12-09 10:06:52 回复(0)
while(line=readline()){
    const ips = line.split('.');
    let res = 'YES';
    for (let i = 0; i < 4; i++) {
        if (ips[i] > 255 || ips[i] < 0) {
            res = 'NO';
        }
    }
    print(res);
}

发表于 2017-09-18 20:54:04 回复(0)
//stringstream 用完之后要清空,否则下次使用之前的值还是保存在那里 #include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main(){
	string str;
	while(getline(cin,str)){
		if(str.find(' ') != string::npos){//首先判断是否存在空格
			cout<<"NO"<<endl;
			continue;
		}
		stringstream ss;
		int flag=0;
		while(!str.empty()){//用‘.‘分割开,各个数字大小是否在限定范围内
			int a,b;
			a=str.find('.');
			if(a!=-1){
				ss<<str.substr(0,a);
				ss>>b;
                ss.clear();
				if(b<0 || b>256){
					cout<<"NO"<<endl;
					flag=1;
					break;
				}
				str=str.substr(a+1,str.length());
			}
			else{//最后一个无法分割,可以直接使用
				ss<<str;
				ss>>b;
                ss.clear();
				if(b<0 || b>256){
					cout<<"NO"<<endl;
					flag=1;
					break;
				}
				str="";
			}
		}
		if(flag==0)
			cout<<"YES"<<endl;
	}
	return 0;
}

编辑于 2017-08-10 18:12:51 回复(1)