博客
关于我
微软高频面试模拟题: 验证合法的ipv4地址
阅读量:225 次
发布时间:2019-03-01

本文共 1369 字,大约阅读时间需要 4 分钟。

- 给定一个字符串,判断是否是有效的IP地址(提示,有效的IP地址格式是xxx.xxx.xxx.xxx, xxx在0-255之间)(输入不保证都是这种格式,要自己判断,同时001这种是否有效要问面试官)

去除开头的空格

输入:IP = "172.16.254.1"输出:"IPv4"解释:有效的 IPv4 地址,返回 "IPv4"

首先想最直接的,允许使用split函数的思路:

思路: 首先一定要有三个点,如果没有三个点,一定是不合法的。然后就可以用split,将每一部分单独拆分出来,变成四部分的字符串数组。

如果其中字符串的长度大于3或者为0,说明一定不合法。按照规定如果第一位是0,并且长度大于1,并且每个字符串只能是数字,而且值不超过255

def validIPv4(self, IP: str) -> bool:        if IP.count('.')!=3:            return False        nums = IP.split('.')        for x in nums:            if len(x)==0 or len(x)>3:                return False            if x[0]=='0' and len(x)>1 or not x.isdigit() or int(x)>255:                return False        return True

 

纯C字符串解析:

bool judgeIPV4(char* s) {    if (!s) return false;    int digit = -1;    count = 0;    while (*s != '\0') {        if (*s >= '0' && *s <= '9' && digit == -1) {            digit = 0;        }        if (*s >= '0' && *s <= '9' && digit != -1) {            int temp = *s - '0';            digit = digit * 10 + temp;            if (digit > 255) {                return false;            }        }         else if(digit == '.') {            if (digit < 0) {                return false;            }            count += 1;            if (count > 3) return false;            digit = -1;        } else {            return false;        }        s++;    }    if (count != 3 || digit < 0) return false;    return true;}

 

 

 

 

 

转载地址:http://vjqv.baihongyu.com/

你可能感兴趣的文章
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>