Type Here to Get Search Results !

Powers Of 2 | Coding Problems In Java |

0

Powers of 2

Description

Write a code that prints the highest power of 2, less than or equal to a given number. For e.g., if the input number is 9, the code should print 8, as 8 or  23 is the highest power of two which is less than 9.

Sample Input:

9

Output:

8

Note: Please enter your inputs in the Input Console before clicking on Test Run.

Execution time limit

15 seconds





Recommended: Please try your approach on your integrated development environment (IDE) first, before moving on to the solution.

Few words from CodingHumans : Don't Just copy paste the solution, try to analyze the problem and solve it without looking by taking the the solution as a hint or a reference . Your understanding of the solution matters.


HAVE A GOOD DAY 😁



Solution:
( java )

import java.util.Scanner;
class CodingHumans{
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int number = scan.nextInt();   // Enter the number
        int result = 1;
        if(number >= 2) {
            while (result * 2 <= number) {
                result = result * 2;
            }
            System.out.print(result);
        } 
        else
        {
            System.out.print("Please enter an integer >= 2");
        }
        scan.close();
    }

}

Post a Comment

0 Comments

Top Post Ad

Below Post Ad