Java coding interview questions:

- Write Java code to calculate the HCF or the greatest common divisor of two numbers. Once you’ve calculated the HCF of two numbers, print out the HCF.

Hint: HCF is the highest number that divides two numbers. So your loop should start by checking if the lower of the two numbers entered is the HCF and then check the numbers below, one by one until the HCF is found.

For e.g., if the numbers entered are 12 and 45, the output is 3.

Sample Input:

12 45

Output:

3

import java.util.Scanner; public class Solution { public static void main(String args[]) { Scanner scan = new Scanner(System.in); // Enter number 1 in the Input Console int num1 = scan.nextInt(); // Enter number 2 in the Input Console int num2 = scan.nextInt(); int hcf = 0; // Write logic if (num1 < num2) { if (num2 % num1 == 0) { hcf = num1; } else { int counter = num2; while (counter > 0) { if (num1 % counter == 0 && num2 % counter == 0) { hcf = counter; break; } counter--; } } } if (num2 < num1) { if (num1 % num2 == 0) { hcf = num2; } else { int counter = num1; while (counter > 0) { if (num1 % counter == 0 && num2 % counter == 0) { hcf = counter; break; } counter--; } } } System.out.print(hcf); scan.close(); } }

## Powers of 2

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 2^{3} is the highest power of two which is less than 9.

Sample Input:

9

Output:

8

Here is the solution.

import java.util.Scanner; class Source { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // Enter the number int number = scan.nextInt(); 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(); } }