牛客华为机试HJ39
作者:互联网
1. 题目描述
2. Solution
1、思路
把ip全转换为32bit 字符串,模拟与运算。
2、实现
import sys
if sys.platform != "linux":
file_in = open("input/HJ39.txt")
sys.stdin = file_in
"""
若IP地址或子网掩码格式非法则输出1,若IP1与IP2属于同一子网络输出0,若IP1与IP2不属于同一子网络输出2。
"""
def is_valid_ip(s):
if ".." in s:
return False
for x in list(map(int, s.split("."))):
if x < 0 or x > 255:
return False
return True
def is_valid_mask(mask):
if not is_valid_ip(mask):
return False
mask_bin = ip2bin(mask)
if '0' not in mask_bin or '1' not in mask_bin or '01' in mask_bin:
return False
return True
def int2bin(n):
n_bin = bin(n).replace("0b", "")
return f'{"0" * (8 - len(n_bin))}{n_bin}'
def ip2bin(s):
nums = list(map(int, s.split(".")))
return "".join([int2bin(x) for x in nums])
def solve(ip1, ip2, mask):
if not is_valid_ip(ip1) or not is_valid_ip(ip2) or not is_valid_mask(mask):
print(1)
return
ip1_bin = ip2bin(ip1)
ip2_bin = ip2bin(ip2)
mask_bin = ip2bin(mask)
for i in range(32):
if mask_bin[i] == '0':
continue
if ip1_bin[i] != ip2_bin[i]:
print(2)
return
print(0)
while True:
try:
mask = input().strip()
ip1 = input().strip()
ip2 = input().strip()
solve(ip1, ip2, mask)
except:
break
标签:bin,return,mask,ip2,牛客,HJ39,ip1,机试,valid 来源: https://www.cnblogs.com/junstat/p/16168268.html