Java: Check whether a given integer is a power of 4 or not
Check Power of 4
Write a Java program to check whether the given integer is a power of 4 or not.
Given num = 64, return true. Given num = 6, return false.
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.Scanner;
public class Example110 {
public static void main(String[] arg) {
int test = 0; // Initialize a variable 'test' to 0
Scanner in = new Scanner(System.in); // Create a Scanner object for user input
System.out.print("Input a positive integer: "); // Prompt the user to input a positive integer
int n = in.nextInt(); // Read the user's input as an integer
if (n < 1) {
System.out.print(Boolean.toString(false)); // If n is less than 1, print "false" and set 'test' to 1
test = 1;
}
if ((n & (n - 1)) != 0) {
System.out.print(Boolean.toString(false)); // If n is not a power of 2, print "false" and set 'test' to 1
test = 1;
}
if (test == 0) {
System.out.print(Boolean.toString((n & 0x55555555) != 0)); // If 'test' is 0, check if n has odd bits set and print the result
}
System.out.print("\n"); // Print a new line
}
}
Sample Output:
Input a positive integer: 64 true
Flowchart:

For more Practice: Solve these Related Problems:
- Modify the program to check if the number is a power of 2 instead.
- Write a program to check if a number is a power of 3.
- Modify the program to find the largest power of 4 less than a given number.
- Write a program to return the exponent when a number is a power of 4.
Java Code Editor:
Previous: Write a Java program to form a staircase shape of n coins where every k-th row must have exactly k coins.
Next: Write a Java program to add two numbers without using any arithmetic operators.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics