Java simple solution


  • 0
    Z

    Two Steps:
    Step 1: Get the two maps mapHour&mapMinute, maps contain the num of LEDs which are on and the possible time string.
    Step 2: List all possible pair of hour and minute given the N

    public List<String> readBinaryWatch(int num) {
        List<String> list_rslt=new ArrayList<>();
        if(num<0)
            return list_rslt;
    
        // Get the two maps mapHour&mapMinute.
        HashMap<Integer,List<String>> mapHour=new HashMap<>();
        HashMap<Integer,List<String>> mapMinute=new HashMap<>();
    
        for(int i=0;i<=59;++i){
            int n=i;
            int count=0;
            while(n!=0){
                if((n&1)>0) ++count;
                n=n>>1;
            }
    
            if(!mapMinute.containsKey(count)){
                List<String> tempList=new ArrayList<>();
                tempList.add(String.format("%02d",i));
                mapMinute.put(count,tempList);
            }else{
                mapMinute.get(count).add(String.format("%02d",i));
            }
    
    
            if (i <= 11) {
                if(!mapHour.containsKey(count)){
                    List<String> tempList=new ArrayList<>();
                    tempList.add(i+":");
                    mapHour.put(count,tempList);
                }else{
                    mapHour.get(count).add(i+":");
                }
            }
    
        }
    
    
    
    
        // List all possible combination of hour and minute given the N.
        int numHour=0,numMin=0;
        for(int i=0;i<=num;++i) {
            numHour=i;
            numMin=num-i;
    
            if(!mapHour.containsKey(numHour)||!mapMinute.containsKey(numMin))
                continue;
    
    
            List<String> listHour=mapHour.get(numHour);
            List<String> listMin=mapMinute.get(numMin);
    
            for (String hour : listHour) {
                for (String min : listMin) {
                    list_rslt.add(hour+min);
                }
            }
    
    
        }
    
    
    
        return list_rslt;
    }

Log in to reply
 

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