Wednesday, 5 October 2016

Binary Watch (LeetCode)

Problem: Binary Watch

class Solution {
public:
    vector<string> readBinaryWatch(int num) {
        vector<string> times;
        int bitmask = 1<<10;
        for(int i=0;i<bitmask;i++)
            if(__builtin_popcount(i)==num)
            {
                int minutes = i % (1<<6);;
                int hour = i / (1<<6);
                if(minutes<60 && hour<12)
                {
                    string s = "";
                    if(hour<10) s+= hour+'0';
                    else 
                    {
                        s += hour/10 + '0';
                        s += hour%10+'0';
                    }
                    s+=':';
                    if(minutes<10)
                    {
                        s += '0';
                        s += minutes+'0';
                    }
                    else 
                    {
                        s += minutes/10+'0';
                        s += minutes%10+'0';
                    }
                    times.push_back(s);
                }
            }
        return times;  
    }
};

No comments:

Post a Comment