第一题想到个方法,用纯真值表和位运算做,考虑单个位置: a=1,b=1 c=0需要两次 c=1不需要 a=0,b=1 c=0需要一次 c=1不需要 (同a=1,b=0) a=0,b=0 c=0不需要 c=1需要一次 因为位运算没有2,所以拆成两个数计算次数 举例d=(a^c)&(b^c) a=1,b=1 c=0,d=1 c=1,d=0 a=0,b=1 c=0,d=0 c=1,d=0 (同a=1,b=0) a=0,b=0 c=0,d=0 c=1,d=1 e同理, a=1,b=1 c=0,e=1 c=1,e=0 a=0,b=1 c=0,e=1 c=1,e=0 (同a=1,b=0) a=0,b=0 c=0,e=0 c=1,e=0 不要觉得d、e奇怪,使用ac、bc真值表凑的 public Integer cal(Integer a,Integer b,Integer c) { int ab = a|b,counter=0, d=(a^c)&(b^c),lastD, e=(ab)^c&(ab),lastE; while(d!=0){ lastD = d % 2; if(lastD==1) counter++; d = d >> 1; } while(e!=0){ lastE = e % 2; if(lastE==1) counter++; e = e >> 1; } return counter; } 没验证过其他的,可以帮我测一下
点赞 评论
牛客网
牛客企业服务