Power of 2


๐Ÿ”น Aim of the Program

Given a positive integer N, check whether it is a power of 2 or not.


๐Ÿง  Algorithm

  1. Read the number of test cases, T.
  2. For each test case:
    • Read the number N.
    • Count the number of 1s in the binary representation of N.
    • If exactly one bit is set (count of 1s == 1), then N is a power of 2.
    • Otherwise, it is not a power of 2.
  3. Print "YES" if it's a power of 2, else "NO".

๐Ÿ’ป C Code


#include <stdio.h>

int main() {
    int itr;
    scanf("%d", &itr);
    while (itr--) {
        long long int num, flag = 0;
        scanf("%lld", &num);
        while (num > 0) {
            if (num & 1) {
                flag++;
            }
            num = num >> 1;
        }
        if (flag == 1)
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

๐Ÿงพ C++ Code


#include <iostream>
using namespace std;

int main() {
    int itr;
    cin >> itr;
    while (itr--) {
        long long num;
        int flag = 0;
        cin >> num;
        while (num > 0) {
            if (num & 1)
                flag++;
            num = num >> 1;
        }
        cout << (flag == 1 ? "YES" : "NO") << endl;
    }
    return 0;
}

โ˜• Java Code


import java.util.Scanner;

public class PowerOfTwo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int itr = sc.nextInt();
        while (itr-- > 0) {
            long num = sc.nextLong();
            int count = 0;
            while (num > 0) {
                if ((num & 1) == 1)
                    count++;
                num = num >> 1;
            }
            System.out.println(count == 1 ? "YES" : "NO");
        }
        sc.close();
    }
}

๐Ÿ Python Code


t = int(input())
for _ in range(t):
    num = int(input())
    count = bin(num).count('1')
    print("YES" if count == 1 else "NO")

๐ŸŒ JavaScript Function


function isPowerOfTwo(n) {
    return (n > 0) && (n & (n - 1)) === 0;
}

// Example usage:
const numbers = [1, 2, 3, 4, 8, 10, 16, 18];
numbers.forEach(num => {
    console.log(`${num} is ${isPowerOfTwo(num) ? "YES" : "NO"}`);
});

No comments:

Post a Comment