Q-3
Single File Programming Question
Your little brother has a math assignment to find whether the given u power of 2. If it is a power of 2 then he has to find the sum of the digit power of 2, then he has to find the next number which is a power of your help to validate his work. But you are already busy playing video games Develop a program so that your brother can validate his work by
Example 1
Input
64
Output
import java.util.Scanner;
public class Main
{
//The function that will will check if a number is power of 2
static boolean power_of_2(int number)
{
if (number == 1)
return true;
else if (number % 2 != 0 ||
number ==0)
return false;
// recursive calling of the function
return power_of_2(number / 2);
}
static int sum_of_Digits(int number)
{
return number == 0 ? 0 : number%10 +
sum_of_Digits(number/10) ;
}
public static int next_power_of_2 ( int number )
{
int val = 1;
while(val<=number)
{
val=val << 1;
}
return val ;
}
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number\n");
n = input.nextInt();
if(power_of_2(n)==true){
System.out.printf("%d is a power of 2\n", n);
System.out.println("The sum of the digits of the number is:\t"+ sum_of_Digits(n));
}
else{
System.out.printf(" %d is not a power of two\n",n);
System.out.println("The next power of two is: "+next_power_of_2(n));
}
}
}
Comments
Leave a comment