Easy Javascript solution explained


  • 0
    R

    If the number of bits in the hour is equal to the requested number of LEDs, then its a valid hour:

    var readBinaryWatch = function(num) {
        var hour,
            minutes,
            numBits,
            result = [],
            hourFormat = "";
        
        for(hour = 0; hour <= 11; hour++){
            for(minutes = 0; minutes <= 59; minutes++){
                // Count the number of 'one' bits in each number
                numBits = hour.toString(2).split(1).length - 1;
                numBits += minutes.toString(2).split(1).length - 1;
                
                // If the number of bits in the hour is the same as the requested number add it to the results
                if(numBits === num){
                    // Format the output, if the minutes are less than 10 add a zero at the beggining of the string
                	hourFormat = hour.toString() + ":" + (minutes < 10? '0' + minutes.toString() : minutes.toString());
                    result.push(hourFormat);
                }
                
            }
        }
        
        return result;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.