Java solution, with generalized purposed functions


  • 0
    H

    Some helper functions are used for support, so if you live in a country where you have 26 hours a day and 76 minutes per hour, you can find these functions very reusable, compare to other posted solutions that writing all the magic numbers in code:

    public class Solution {
        
        private  HashMap<Integer, List<String>> htable;
        private  HashMap<Integer, List<String>> mtable;
        
        public List<String> readBinaryWatch(int num) {
            
            List<String> ret = new ArrayList<String>();
            
            // edge case, num should be within [0, 10]
            if (num < 0 || num > 10)
                return ret;
                
           htable = new HashMap<Integer, List<String>>();
           mtable = new HashMap<Integer, List<String>>();
            
            construct_tables(htable, 4, 11, false);
            construct_tables(mtable, 6, 59, true);
            
            // h is in [0,3]
            for (int h = 0; h <= 3; h++) {
                int m = num - h;
                
                // invalid minutes digit, m is in [0,5]
                if (m < 0 || m >= 6)
                    continue;
                
                List<String> times = calculate_time(h, m);
                ret.addAll(times);
            }
            
            return ret;
            
        }
        
        private void construct_tables(HashMap<Integer, List<String>> table, int num, int max, boolean pad) {
            
            int[] slots = new int[num];
            
            for (int i = 0; i < num; i++) {
                slots[i] = 1 << i;
            }
            
            for (int i = 0; i <=max; i++) {
                
                int filled = 0;
                for (int j = 0; j < num; j++) {
                    if ((slots[j] & i) != 0)
                        filled++;
                }
                
                List<String> arr = table.get(filled);
                if (arr == null)
                    arr = new ArrayList<String>();
                    
                if (pad && i < 10)
                    arr.add("0" + i);
                else 
                    arr.add(Integer.toString(i));
                
                table.put(filled, arr);
                
            }
            
        }
        
        // hour is in [0, 3] and time is in [0,5]
        private List<String> calculate_time(int hour, int minute) {
            List<String> time = new ArrayList<String>();
            
            for (String h : htable.get(hour)) {
                for (String m : mtable.get(minute)) {
                    time.add(h+":"+m);
                }
                
            }
            
            return time;
            
        }
        
        
    }
    

Log in to reply
 

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