《Cracking the Coding Interview》——第5章:位操作——题目3
2014-03-19 06:15
447 查看
2014-03-19 05:57
题目:给定一个整数N,求出比N大,而且二进制表示中和N有相同个数的‘1’的最小的数,比如3是‘11’,接下来的5是‘101’,再接下来的6是‘110’。
解法:从低位往高位,首先跳过连续的‘0’,然后跳过连续的‘1’,并数数有多少个1。如果这时还没到最高位,那就从刚才跳过的‘1’中拿出1个放到这位上(当前位是‘0’),然后把剩下的‘1’填到最低的几位上去。中间填充‘0’。比如:‘100111000’的下一个是‘101000011’
代码:
题目:给定一个整数N,求出比N大,而且二进制表示中和N有相同个数的‘1’的最小的数,比如3是‘11’,接下来的5是‘101’,再接下来的6是‘110’。
解法:从低位往高位,首先跳过连续的‘0’,然后跳过连续的‘1’,并数数有多少个1。如果这时还没到最高位,那就从刚才跳过的‘1’中拿出1个放到这位上(当前位是‘0’),然后把剩下的‘1’填到最低的几位上去。中间填充‘0’。比如:‘100111000’的下一个是‘101000011’
代码:
// 5.3 Find the next largest number that have same number of '1's with the given number. #include <cstdio> using namespace std; unsigned int findNext(unsigned int n) { int n_zero; int n_one; n_zero = 0; while (n_zero < 32 && (n & (1 << n_zero)) == 0) { ++n_zero; } if (n_zero == 32) { // all 0 return n; } n_one = n_zero; while (n_one < 32 && (n & (1 << n_one)) != 0) { ++n_one; } if (n_one == 32) { // no larger number is possible return n; } n = n >> n_one << n_one; n |= (1 << n_one); for (int i = 0; i < n_one - n_zero - 1; ++i) { n |= (1 << i); } return n; } int main() { unsigned int n; while (scanf("%u", &n) == 1) { printf("%u\n", findNext(n)); } return 0; }
相关文章推荐
- 《Cracking the Coding Interview》——第5章:位操作——题目1
- 《Cracking the Coding Interview》——第5章:位操作——题目2
- 《Cracking the Coding Interview》——第5章:位操作——题目4
- 《Cracking the Coding Interview》——第5章:位操作——题目5
- 《Cracking the Coding Interview》——第5章:位操作——题目6
- 《Cracking the Coding Interview》——第5章:位操作——题目7
- 《Cracking the Coding Interview》——第5章:位操作——题目8
- 《Cracking the Coding Interview》——第13章:C和C++——题目8
- 《Cracking the Coding Interview》——第14章:Java——题目4
- 《Cracking the Coding Interview》——第17章:普通题——题目6
- 《Cracking the Coding Interview》——第18章:难题——题目1
- 《Cracking the Coding Interview》——第2章:链表——题目5
- 《Cracking the Coding Interview》——第4章:树和图——题目7
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目1
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目2
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目7
- 《Cracking the Coding Interview》——第14章:Java——题目5
- 《Cracking the Coding Interview》——第18章:难题——题目2
- 《Cracking the Coding Interview》——第2章:链表——题目6
- 《Cracking the Coding Interview》——第4章:树和图——题目8