Pages

Friday, May 2, 2025

Check for power of 2 in Bit Manipulation in C++

 #include <iostream>

using namespace std;


bool isPowerOf2(int num) {

    if (!(num & (num-1))) { // if not equal to num & num-1

        return true;

    } else {

        return false;

    }

}



int main()

{

    cout << isPowerOf2(4) << endl;

    cout << isPowerOf2(16) << endl;

    cout << isPowerOf2(13) << endl;

    cout << isPowerOf2(7) << endl;


    return 0;

}

No comments:

Post a Comment

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...