位操作-leetcode 401. Binary Watch
2017-07-03 19:27
337 查看
原题链接:Binary Watch
题解:
class Solution {
public:
//计算1的位数
int countBits(int n){
if(n==0)return 0;
int count=1;
while(n=n&(n-1))count++;
return count;
}
vector<string> readBinaryWatch(int num) {
/*
Time Complexity:O(1)
Space Complexity:O(1)
*/
vector<string>svec;
if(num<0 || num>8 )return svec;
if(num==0)return vector<string>{"0:00"};
vector<int>hours;
for(int i=0;i<=3&&i<=num;i++){
hours.clear();
for(int temp=0;temp<=11;temp++){
if(countBits(temp)==i){
hours.push_back(temp);
}
}
for(int temp=0;temp<=59;temp++){
if(countBits(temp)==num-i){
for(int k=0;k<hours.size();k++){
svec.push_back(to_string(hours[k])+":"+((temp<10)?("0"+to_string(temp)):to_string(temp)));
}
}
}
}
return svec;
}
};
题解:
class Solution {
public:
//计算1的位数
int countBits(int n){
if(n==0)return 0;
int count=1;
while(n=n&(n-1))count++;
return count;
}
vector<string> readBinaryWatch(int num) {
/*
Time Complexity:O(1)
Space Complexity:O(1)
*/
vector<string>svec;
if(num<0 || num>8 )return svec;
if(num==0)return vector<string>{"0:00"};
vector<int>hours;
for(int i=0;i<=3&&i<=num;i++){
hours.clear();
for(int temp=0;temp<=11;temp++){
if(countBits(temp)==i){
hours.push_back(temp);
}
}
for(int temp=0;temp<=59;temp++){
if(countBits(temp)==num-i){
for(int k=0;k<hours.size();k++){
svec.push_back(to_string(hours[k])+":"+((temp<10)?("0"+to_string(temp)):to_string(temp)));
}
}
}
}
return svec;
}
};
相关文章推荐
- Leetcode 401. Binary Watch
- Leetcode: 401. Binary Watch
- [LeetCode]401. Binary Watch &bitset的用法&to_string
- LeetCode-Backtracking-401. Binary Watch
- LeetCode 401. Binary Watch
- [leetcode]: 401. Binary Watch
- leetcode 401. Binary Watch
- [leetcode: Python]401. Binary Watch
- 【LeetCode】401. Binary Watch
- LeetCode-401. Binary Watch
- [LeetCode]401. Binary Watch
- 【Leetcode】401. Binary Watch
- leetCode 401. Binary Watch
- Leetcode-401. Binary Watch
- LeetCode Rotate List (链表操作)
- LeetCode_链表操作1—Swap Nodes in Pairs
- 关于leetcode中链表操作的的几道题。
- [LeetCode] Isomorphic Strings - 字符串操作:数组计数字符个数问题
- leetcode -- Text Justification -- string操作的题目,思路简单,但是难以写对
- LeetCode-Partition List-分割链表-链表操作