Answer to Question #233637 in Java | JSP | JSF for Bhitg

Question #233637
little brother has a maths assignment to find whether the given number is a power of 2 if it is a power of 2 then he has to find the sum of digits if it is not
1
Expert's answer
2021-09-06T01:59:27-0400
import java.util.Scanner;




public class Main
{


static boolean power_2(int nu)
{
  
  if (nu== 1)
    return true;
 
  
  else if (nu % 2 != 0 ||
           nu ==0)
    return false;
 
  
  return power_2(nu/ 2);
}
 static int sumOfDigits(int n)
    {
        return n== 0 ? 0 : n%10 + 
                  sumOfDigits(n/10) ;
    }
	
public static int  nextPowerOfTwo ( int  n )
{
	int v = 1;
	 
	
	while(v<=n)
	{
		v=v<< 1;
	}
	return v;
}
	public static void main(String[] args) {




int number;




Scanner input = new Scanner(System.in);
System.out.println("Enter number\n");
number = input.nextInt();
if(power_2(number)==true){
    System.out.println(number+ " is a power of 2\n");
    System.out.printf("Sum of %d digits is: %d\n",number, sumOfDigits(number));




}
else{
  System.out.println(number+"  is not a power of two\n");
  System.out.printf("The next power of two is:  "+nextPowerOfTwo(number));
}








	
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS