【c++算法】《判断一个数是否为2的n次方》

    技术2025-04-21  4

    判断一个数是否为2的n次方。

    #include <iostream> using namespace std; bool is2N(int dest) { if (dest & (dest - 1)) //核心代码 return false; else return true; } int main() { if (is2N(4)) { cout << "4是2的N次方" << endl; } else { cout << "4不是2的N次方" << endl; } }

    如上若不理解if (dest & (dest - 1)) //核心代码;可以查看我另一篇博客: c/c++的位运算符使用技巧

    若是2的n次方的数,它的反码中最后一位必然不是1;同理2的n次方-1的数,必然是奇数,反码最后一位必然为1

    判断某个区间的数中为2的n次方的数。

    上面已经展示过了判断一个数是否为2的n次方的算法了,这里我们来拓展一下,判断自然数0~N中为2的n次方的数字。

    #include <iostream> using namespace std; void find2N(int dest) { for (size_t i = 0; i < dest; i++) { if (i & (i - 1)) { continue; } cout << i << endl; } } int main() { find2N(100); }

    版权声明:转载标明出处

    Processed: 0.016, SQL: 9