bit count java


  • 0
    R
    public class Solution {
        public List<String> readBinaryWatch(int num) {
            
            List<String> res = new ArrayList<>();
                
            for(int i = 0; i < 12; i++ ){
                int top = i;            //  hour
                int countTop = 0;     // count bit turned on (ones)
                while( top != 0 ){
                    if( (top & 1) == 1 ) countTop++;
                    top >>= 1;
                }
                if( countTop > num )    continue;
                for(int j = 0; j < 60; j++ ){
                    int bottom = j;                  // minute
                    int countBot = 0;
                    while( bottom != 0 ){
                        if( (bottom & 1) == 1)  countBot++;
                        bottom >>= 1;
                    }
                    if( countBot + countTop == num ){
                        res.add( i + ":" + ( j < 10 ? "0" + j : "" + j ) );
                    }
                }
            }
            
            return res;
        }
    }
    

Log in to reply
 

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