题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import sys #判断ip是否合法,判断每段是否在0-255之间 def check_ip(ip): ips = list(map(int,ip.split('.'))) if len(ips) < 4: return False for i in ips: if i < 0 or i > 255: return False return True #判断掩码是否合法 #先判断是否每段在0-255之间 def check_mask(mask): if not check_ip(mask): return False masks = list(map(int, mask.split('.'))) mask_str = "" for m in masks: #转成二进制形式的字符串,注意左边要用0补够8位 mask_str += bin(m)[2:].rjust(8,'0') index = mask_str.index('0') # print(mask_str) # print(index) #如果0后面还有1,就是非法 if -1 != index: if '1' in mask_str[index:]: return False return True def convert_int(ipstr): ips = list(map(int, ipstr.split('.'))) ipnum = 0 for ip in ips: ipnum = ip + (ipnum << 8) return ipnum #判断是否同一子网 #ip分别与掩码与,再对比 def check_ziwang(mask, ip1, ip2): mm = convert_int(mask) ipnum1 = convert_int(ip1) ipnum2 = convert_int(ip2) # print(mm & ipnum1) # print(mm & ipnum2) return (mm & ipnum1) == (mm & ipnum2) while True: try: mask = input() ip1 = input() ip2 = input() if not check_ip(ip1) or not check_ip(ip2) or not check_mask(mask): print("1") elif check_ziwang(mask, ip1, ip2): print("0") else: print("2") except: # print(sys.exc_info()) break