CC-1 : Check if number is a power of 3.
Description:
Given an input number check if it is a power of 3.
Test cases and expected outputs:
| Input Parameters |
Expected outputs |
| Number: 10
|
Is Number is power of 3: false
|
| Number: 6
|
Is Number is power of 3: false
|
| Number: 9
|
Is Number is power of 3: true
|
Pseudocode:
checkIfPowerOf3(num):
| The number to be checked is received as input parameter.
|
| If num==1, return true.
|
| If num==0, return false.
|
| Recursively call method checkIfPowerOf3() with argument num/3.
|
Code:
public boolean checkIfPowerOf3(int num){
if (num==1) {
return true;
}
if (num==0) {
return false;
}
if (num %3 !=0 ) {
return false;
}
return checkIfPowerOf3(num/3);
}
Click here to download and run code and test cases !
Below fully running code can be copied and run on Eclipse or other Java IDEs. Refer the classname in code below. If the class name below is "A", save the code below to a file named A.java before running it.
Be sure to try your own test cases to enhance your understanding !
You can also tweak the code to optimize or add enhancements and custom features.
public class RecursionCheckIfPowerOf3 {
public boolean checkIfPowerOf3(int num){
if (num==1) {
return true;
}
if (num==0) {
return false;
}
if (num %3 !=0 ) {
return false;
}
return checkIfPowerOf3(num/3);
}
public static void main(String[] args) {
/***********************
Test cases given below:
**********************/
boolean retVal;
try {
RecursionCheckIfPowerOf3 rcn=new RecursionCheckIfPowerOf3();
int num=10;
retVal=rcn.checkIfPowerOf3(num);
System.out.println("Number: "+num);
System.out.println("Is Number is power Of 3 "+retVal);
System.out.println();
num=6;
retVal=rcn.checkIfPowerOf3(num);
System.out.println("Number: "+num);
System.out.println("Is Number is power Of 3 "+retVal);
System.out.println();
num=9;
retVal=rcn.checkIfPowerOf3(num);
System.out.println("Number: "+num);
System.out.println("Is Number is power Of 3 "+retVal);
}catch (Exception exception) {
System.out.print("Exception: "+ exception);
exception.printStackTrace();
}
}
}