Straightforward iterative method, Java, beats %55


  • 0
    V
    public class Solution {
    
    public static List<String> readBinaryWatch(int num) {
        
        List<String> result = new ArrayList<>();
        List<Integer> hours = getPossibleHours(num);
        List<Integer> mins = getPossibleMinutes(num);
        
        for(int i = 0; i < hours.size(); i++){
            for (int j = 0; j < mins.size(); j++) {
                if(getOnes( hours.get(i) ) + getOnes( mins.get(j) ) == num){
                    String rep = getStringRep(hours.get(i), mins.get(j));
                    result.add(rep);
                }
            }
        }
        
        return result;
    }
    private static int getOnes(int num){
        int count = 0;
        for(int i = 0; i < 32; i++){
            count += ( num >> i ) & 1;
        }
        return count;
    }
    private static List<Integer> getPossibleMinutes(int num){
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i <= 59; i++) {
            if(getOnes(i) <= num)
                res.add(i);
        }
        return res;
    }
    private static List<Integer> getPossibleHours(int num){
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i <= 11; i++) {
            if(getOnes(i) <= num)
                res.add(i);
        }
        return res;
    }
    private static String getStringRep(int i, int j) {
        StringBuilder sb = new StringBuilder();
        sb.append(Integer.toString(i));
        sb.append(":");
        if(j < 10)
            sb.append("0");
        sb.append(Integer.toString(j));
        return sb.toString();
    }
    

    }


Log in to reply
 

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