Java two loops, using bitCount, beat 90%


  • 2
        public List<String> readBinaryWatch(int num) {
            int bitCount = 0;
        	List<String> ls = new ArrayList<String>();
        	
        	for(int i=0; i<12;i++){
        		for(int j=0; j<60;j++){
        			bitCount = Integer.bitCount(i)+Integer.bitCount(j);
        			if (bitCount==num){
        				if(j<10){
        					ls.add(i+":0"+j);
        				}else{
        					ls.add(i+":"+j);
        				}
        			}
        		}
        	}
        	return ls;
        }

  • 0
    R

    how did you come up with this :)


  • 0
    R

    @Lindsayling it can be more shortcut.
    No need to compute hour bit counts each time. And when num is less than hour bit counts, just skip to next loop.

    public List<String> readBinaryWatch(int num) {
            List<String> times = new ArrayList<>();
            for(int h=0; h <12; ++h) {
                int b1 = Integer.bitCount(h);
                if(b1 > num) continue;
                for(int m=0; m < 60; ++m) {
                    if(Integer.bitCount(m) == num - b1) {
                        times.add(h + ":" + (m < 10 ? "0" : "") + m);
                    }
                }
            }
            return times;
        }
    

Log in to reply
 

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