题解 | #验证IP地址#

验证IP地址

https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
class Solution:
    def solve(self, IP: str) -> str:
        # write code here
        if "." in IP:
            blocks = IP.split(".")
            if len(blocks) != 4:
                return "Neither"
            for block in blocks:
                try:
                    int(block)
                except:
                    return "Neither"
                if (
                    not block
                    or len(str(int(block))) != len(block)
                    or not 0 <= int(block) <= 255
                ):
                    return "Neither"
            return "IPv4"
        if ":" in IP:
            blocks = IP.split(":")
            if len(blocks) != 8:
                return "Neither"
            for block in blocks:
                if not block or len(block) > 4:
                    return "Neither"
                try:
                    int(block, 16)
                except:
                    return "Neither"
                if int(block, 16) == 0 and len(block) > 1:
                    return "Neither"
            return "IPv6"
        return "Neither"

全部评论

相关推荐

牛客36400893...:我不是这个专业的,但是简历确实没有吸引我的亮点,而且废话太多没耐心看
0offer是寒冬太冷还...
点赞 评论 收藏
分享
Java转测开第一人:这种就是饼 把应届当廉价劳动力用完然后丢掉
你觉得今年秋招难吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务