Write a program to check given number is the power of 2
Example 1:
Input: num=4
Output: Power of 2
Example 2:
Input: num=5
Output: Not power of 2
Approach:
Java
public class NumberPower2 {public static void main(String[] args) {int num = 64;if (isPowerOfTwo(num)) {System.out.println("Power of 2");} else {System.out.println("Not Power of 2");}}private static boolean isPowerOfTwo(int num) {// base caseif (num == 0)return false;while (num != 1) {// if number is not divisible by 2if (num % 2 != 0) {return false;}num /= 2;}return true;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check for//power of 2bool isPowerOfTwo(int n){//base caseif(n==0)return false;//itearte till n is not 1 or nwhile(n!=1){//if number is odd then not//power of 2 return falseif(n&1)return false;//else divide by 2n=n/2;}//return truereturn true;}int main(){int num=4;if(isPowerOfTwo(num))cout<<"Power of 2\n";elsecout<<"Not power of 2\n";return 0;}//Time Complexity: O(log(n))
No comments:
Post a Comment