You can check if a number is a power of 2 using recursion in Java by repeatedly dividing the number by 2 and checking if it eventually becomes 1. If it does, then it’s a power of 2. Here’s a Java code example to achieve this:
public class PowerOfTwoChecker {
public static void main(String[] args) {
int number = 16; // Change this to the number you want to check
if (isPowerOfTwo(number)) {
System.out.println(number + " is a power of 2.");
} else {
System.out.println(number + " is not a power of 2.");
}
}
public static boolean isPowerOfTwo(int n) {
// Base case: If n becomes 1, it's a power of 2.
if (n == 1) {
return true;
}
// If n is not divisible by 2 or is less than 1, it's not a power of 2.
if (n % 2 != 0 || n < 1) {
return false;
}
// Recursively check the result of dividing n by 2.
return isPowerOfTwo(n / 2);
}
}
In this code, the isPowerOfTwo
method checks if the number n
is a power of 2 by recursively dividing it by 2 until it becomes 1 or no longer divisible by 2. If it reaches 1, it returns true
; otherwise, it returns false
. You can change the number
variable to any integer you want to check.
Problem source: https://leetcode.com/problems/power-of-two/