按位与 | HJ39 判断两个IP是否属于同一子网
# 最优解 while 1: try: mask = list(map(int, input().split('.'))) ip1 = list(map(int, input().split('.'))) ip2 = list(map(int, input().split('.'))) f = True for i in range(len(mask)): if mask[i] not in range(256) or ip1[i] not in range(256) or ip2[i] not in range(256): f = False break if i<len(mask)-1 and mask[i] < mask[i+1]: f = False break t1,t2= [],[] if f: for i in range(len(mask)): t1.append(mask[i]&ip1[i]) t2.append(mask[i]&ip2[i]) if t1==t2: print(0) else: print(2) else: print(1) except:break # 我的代码 def is_ip_valid(ip): for seg in ip: if int(seg) < 0 or int(seg) > 255: return False return True def is_mask_valid(mask): if not is_ip_valid(mask): return False bin_mask = '' for seg in mask: bin_seg = '{:0>8}'.format(bin(int(seg))[2:]) bin_mask += bin_seg for i in range(1, 33): tmp = bin_mask[i:] if bin_mask[i]=='0': return int(tmp) == 0 def mask_ip(ip, maks): res = [] for ip_seg, mask_seg in zip(ip, mask): res.append(str(int(ip_seg) & int(mask_seg))) return '.'.join(res) while True: try: mask = input().split('.') ip1 = input().split('.') ip2 = input().split('.') if not is_ip_valid(ip1) or not is_ip_valid(ip2) or not is_mask_valid(mask): print(1) else: res1 = mask_ip(ip1, mask) res2 = mask_ip(ip2, mask) if res1 == res2: print(0) else: print(2) except: break
用时:30min
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107