Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

401. Binary Watch #121

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

bitCount 方法是用来统计参数i转成2进制后有多少个1 而不是统计补码有多少个一。 方法也大致解释下 能看懂就扩展下自己的思路,不懂的话就记住吧。 i = i - ((i >>> 1) & 0x55555555); 把i的二进制 两位一组统计1的数目

i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);把刚才的结果4位一组 统计 1的数目 i = (i + (i >>> 4)) & 0x0f0f0f0f; 8位1组统计 i = i + (i >>> 8); 16位一组统计 结果放在 后8位

i = i + (i >>> 16); 32位1组统计 结果放在 后16位 整数固定是32位 i & 0x3f 由于8位以上统计时 并没有过滤掉高位的数字,所以在这里过滤掉无效的数字。得到含有1的数目

%d就是普通的输出了 %2d是将数字按宽度为2,采用右对齐方式输出,若数据位数不到2位,则左边补空格 %02d,和%2d差不多,只不过左边补0 %.2d没见过,但从执行效果来看,和%02d一样

public class Solution { public List readBinaryWatch(int num) { List list = new ArrayList(); for(int h = 0; h < 12; h++) { for(int m = 0; m < 60; m++) { if(Integer.bitCount(h*64 + m) == num) { list.add(String.format("%d:%02d", h, m)); } } } return list; } }

Shawngbk commented 7 years ago

google