Likou 401. Binary Watch

Title description

There are 4 LEDs on the top of the binary watch for hours (0-11), and the 6 LEDs on the bottom for minutes (0-59).
Each LED represents a 0 or 1, with the lowest bit on the right.

Insert picture description here

For example, the binary watch above reads "3:25".

Given a non-negative integer n representing the current number of LEDs on, return all possible times.

Example:

Input: n = 1
Return: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, "0:08", "0:16", "0:32"]

prompt:

The order of output is not required.
The hour will not start with a zero. For example, "01:00" is not allowed, it should be "1:00".
The minute must consist of two digits and may start with a zero. For example, "10:2" is invalid and should be "10:02".
Data that exceeds the display range (hours 0-11, minutes 0-59) will be discarded, that is to say, "13:00", "0:61" and other times will not appear.

Problem solving ideas

Use the Hamming weight function to calculate the number of 1 in the binary string corresponding to the decimal number. If the sum of the Hamming weight of the hour number and the minute number is exactly num, then output the time at this time

Code

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

 int hammingWeight(int n) {
    
    
    int result=0;
    while(n)
    {
    
    
        result+=n%2;
        n>>=1;
    }
    return result;
}

char ** readBinaryWatch(int num, int* returnSize){
    
    
  char **re =(char**)calloc(500,sizeof(char*));
  int hour=0;
  int minute=0;
  *returnSize=0;
  for(hour=0;hour<12;++hour){
    
    
      for(minute=0;minute<60;++minute){
    
    
          if(hammingWeight(hour)+hammingWeight(minute)==num){
    
    
              re[*returnSize]=(char*)calloc(6,sizeof(char));
              sprintf(re[*returnSize],"%d:%02d",hour,minute);
              ++(*returnSize);
          }
      }
  }return re;
}

LeetCode link

Guess you like

Origin blog.csdn.net/qq_44722674/article/details/111808355