题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
主要是这个AND运算有点奇怪,不仔细看读不懂
def ten2two(ten): result = "" while ten != 0: result = str(ten % 2) + result ten = ten // 2 if not result: return '00000000' if len(result) != 8: result = '0'*(8-len(result))+result return result def two2ten(n): lst=list(str(n)) quanzhong=len(lst)-1 a=0 for i in lst: a=a+int(i)*2**quanzhong quanzhong=quanzhong-1 return a def is_t(x, y, z): td = [x, y, z] for p in td: y = list(map(int, p.split('.'))) for i in y: if i < 0&nbs***bsp;i > 255: return False x = list(map(int, x.split('.'))) if x[0] != 255: return False if x[-1] != 0: return False return True def is_bin(x, y, z): td = [x, y, z] cd = [] for p in td: y = list(map(int, p.split('.'))) rd = [] for i in y: cc = ten2two(i) rd.append(cc) cd.append(rd) an1 = get_and(cd[0], cd[1]) an2 = get_and(cd[0], cd[2]) if an1 == an2: return 0 else: return 2 def get_and(a, b): res = [] for n, i in enumerate(a): x = list(i) y = list(b[n]) z = '' for n1, t in enumerate(x): if t == '0'&nbs***bsp;y[n1] == '0': q = '0' else: q = '1' z = z+q z = two2ten(z) res.append(z) return res while True: try: a1 = input() a2 = input() a3 = input() if not is_t(a1, a2, a3): print(1) else: ss = is_bin(a1, a2, a3) print(ss) except EOFError: break