- 二进制手表
二进制手表顶部有 4 个 LED 代表 小时(0-11),底部的 6 个 LED 代表 分钟(0-59)。
每个 LED 代表一个 0 或 1,最低位在右侧。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int hammingWeight(int n) {
int result=0;
while(n)
{
result+=n&1;
n>>=1;
}
return result;
}
char ** readBinaryWatch(int num, int* returnSize){
char **re =(char**)calloc(500,sizeof(char*));
int hour=0;
int minute=0;
if(num>9) return '[]';
*returnSize=0;
for(hour=0;hour<12;++hour){
int hour_num = hammingWeight(hour);
if(hour_num>num) continue;
for(minute=0;minute<60;++minute){
int minute_num=hammingWeight(minute);
if(minute_num>num) continue;
if(hour_num+minute_num==num){
re[*returnSize]=(char*)calloc(6,sizeof(char));
sprintf(re[*returnSize],"%d:%02d",hour,minute);
++(*returnSize);
}
}
}return re;
}
这道题中的 sprintf(re[*returnSize],"%d:%02d",hour,minute); 很好用