首页 > 试题广场 >

合法IP

[编程题]合法IP
  • 热度指数:241042 时间限制: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)
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		while (scanner.hasNext()) {
			int count=0;
			String ip = scanner.nextLine();
			for (int i = 0; i < ip.split("\\.").length; i++) {
				if (Integer.valueOf(ip.split("\\.")[i]) > 255 || Integer.valueOf(ip.split("\\.")[i]) < 0) {
					count++;
					break;
				}
			}
			if (count > 0) {
				System.out.println("NO");
			}else {
				System.out.println("YES");
			}
		}
	}
}

发表于 2021-09-07 20:11:45 回复(0)
#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)
JavaScript用四行代码搞定(正则表达式)
while (line = readline()) {
    const regOne = '(([0-9])|([1-9][0-9])|([1][0-9]{2})|([2](([0-4][0-9])|([5][0-5]))))'
    print(new RegExp(`^(${regOne}\\.){3}(${regOne})$`).test(line)? "YES":"NO");
}

每个IP都有如下情况
1位数 0-9
2位数 开头不能为零,即[1-9][0-9]
3位数 [2](([0-4][0-9])|([5][0-5]))
    第一位为1 [1][0-9]{2}  
    第一位为2, 第二位数为0-5, 其中第二位为5的时候 ,第三位为0-5
前三个IP必须带一个.   必须全部字符创都是这样的--加前后判断 (/^XXX$/)


发表于 2022-04-14 17:51:45 回复(0)
懂得人已经给我点赞了
while True:
    try:
        s = input().split('.')
        if len(s) != 4:
            print('NO')
        else:
            for i in s:
                if i == "":
                    print('NO')
                    break
                elif int(i)<0 or int(i)>255:
                    print('NO')
                    break
                elif not i.isdigit():
                    print('NO')
                    break
                elif len(i) != 1 and i.startswith('0'):
                    print('NO')
                    break
            else:
                print('YES')
    except:
        break

发表于 2022-03-07 17:17:36 回复(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)
Java:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s = sc.nextLine();
            System.out.println(isValidIp(s) ? "YES" : "NO");
        }
        sc.close();
    }

    private static boolean isValidIp(String input) {
        String[] ss = input.split("\\.");
        if (ss.length != 4) return false;
        for (String s : ss) {
            int a = Integer.parseInt(s);
            if (a < 0 || a > 255) return false;
        }
        return true;
    }
}

C++:
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

bool is_valid(string &s) {
    stringstream ss(s);
    int count = 0;
    string t;
    while (getline(ss, t, '.')) {
        count++;
        long val = stoi(t, 0, 10);
        if (val < 0 || val > 255) return false;
    }
    if (count != 4) return false;
    return true;
}

int main() {
    string s;
    while (cin >> s) {
        cout << (is_valid(s) ? "YES" : "NO") << endl;
    }
    return 0;
}

C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int is_valid_ip(char *s) {
    int total = 0;
    char *p = strtok(s, " ");
    while (p) {
        int val = atoi(p);
        if (val < 0 || val > 255)return 0;
        p = strtok(NULL, " ");
        total++;
    }
    if (total != 4) return 0;
    return 1;
}

int main() {
    char s[4096] = {0};
    while (gets(s)) {
        printf(is_valid_ip(s) ? "YES\n" : "NO\n");
    }
    return 0;
}


编辑于 2021-01-25 16:11:53 回复(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:
        s = input().split('.')
        for i in s:
            if 0 <= int(i) <= 255:
                pass
            else:
                print('NO')
                break
        else:
            print('YES')
    except:
        break

发表于 2020-03-30 19:12:16 回复(1)
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)