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