题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import copy mask = list(map(int, input().split('.'))) ip1 = list(map(int, input().split('.'))) ip2 = list(map(int, input().split('.'))) def isValidMask(in_mask): into_ones = 0 # print(in_mask) in_mask_1 = copy.deepcopy(in_mask) in_mask_1.reverse() for seg in in_mask_1: if seg < 0 or seg >255: return False elif into_ones and seg < 255: # print('jjjjj') return False else: while seg > 0: # print(seg, into_ones) tmp = seg * 1 seg = seg >> 1 # print(tmp, seg, tmp-(seg<<1), into_ones) if (not tmp-(seg<<1)) and into_ones: # 加减运算优先级高于移位运算 # print('iiii') return False elif tmp-(seg<<1) and not into_ones: into_ones = 1 if into_ones: # print('bbbbb') return True else: # print('is invalid mask') return False # all zeroes def isValidIP(in_ip): for seg in in_ip: if not 0 <= seg <= 255: return False return True masked_ip1 = [] masked_ip2 = [] is_same = 1 if not (isValidMask(mask) and isValidIP(ip1) and isValidIP(ip2)): # print(isValidMask(mask)) print(1) else: # print(mask) for i in range(len(mask)): if mask[i]&ip1[i] != mask[i]&ip2[i]: # print(mask[i]&ip1[i]) print(2) is_same = 0 break if is_same: print(0)
关键在于判断子网掩码是否有效,三个条件:
- 0-255之间
- 第一个seg碰到1之后,后面的seg全是255
- 任一seg碰到1之后,其后面的元素都要通过 n-(n>>1<<1)来判断末尾是否为1