Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Convert c++ Program to Java. Instead of hardcoding numbers in get a input from t

ID: 3879029 • Letter: C

Question

Convert c++ Program to Java. Instead of hardcoding numbers in get a input from the user as well to check if it is a power of 2. MUST BE RECURSIVE.

1 #include<iostream>
2 #include<stdbool.h>
3 #include<math.h>
4 using namespace std;
5 /* Function to check if x is power of 2 or not */
6 bool isPowerOf2(int n)
7 {
8 if (n == 0)
9 return false;
10 while (n != 1)
11 {
12 if (n%2 != 0) //Check for remainder if it non zero then not a power of 2
13 return false;
14 return isPowerOf2(n/2); //recursive call to the function
15 }
16 return true;
17 }
18
19 // Driver program
20 int main()
21 {
22 isPowerOf2(128)? printf("Yes "): printf("No ");
23 isPowerOf2(257)? printf("Yes "): printf("No ");
24 isPowerOf2(1023)? printf("Yes "): printf("No ");
25 isPowerOf2(8192)? printf("Yes "): printf("No ");
26 isPowerOf2(65536)? printf("Yes "): printf("No ");
27 return 0;
28 }

Explanation / Answer

import java.util.Scanner;

class Main {
// METHOD that takes integer n
// logic remains the same
// boolean is variable type in java for bool in cpp
  public static boolean isPowerOf2(int n)
{
if (n == 0)
return false;
while (n != 1)
{
if (n%2 != 0)
return false;
return isPowerOf2(n/2);
}
return true;
}


public static void main(String[] args)
{
// existing cases for testing
if(isPowerOf2(128))
System.out.println("Yes");
else
System.out.println("No");
  
if(isPowerOf2(257))
System.out.println("Yes");
else
System.out.println("No");
  
if(isPowerOf2(1023))
System.out.println("Yes");
else
System.out.println("No");
  
if(isPowerOf2(8192))
System.out.println("Yes");
else
System.out.println("No");
  
if(isPowerOf2(65536))
System.out.println("Yes");
else
System.out.println("No");

// taking user input
Scanner sc = new Scanner(System.in);
System.out.print("Enter a numer: ");
int a = sc.nextInt();
  
// printing output
if(isPowerOf2(a))
System.out.println("Yes");
else
System.out.println("No");
}
}

/*SAMPLE OUTPUT
Yes
No
No
Yes
Yes
Enter a numer: 16
Yes
*/