JAVA
Write a method that finds out if a number is a power of two. Create a tester to demonstrate if it works.
//IsPowerOf2.java import java.util.Scanner; public class IsPowerOf2 { public static boolean isPowerOfTwo(int n){ if(n==0) return false; return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2))))); } // Testing public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int n = scanner.nextInt(); if(isPowerOfTwo(n)){ System.out.println(n+" is a power of 2"); } else{ System.out.println(n+" is NOT a power of 2"); } } }
Get Answers For Free
Most questions answered within 1 hours.