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