Java – Exam – Three largest Numbers
This trivial task was given at the SoftUni exam for Java. There are not a lot of problems that I can solve, but this one was definitely one of them 🙂
So, what is the input and what is the output? At first you are given a number (n), and then you are given n different numbers. As an output you should display the top 3 (or 2, if 2 numbers are given).
| Input | Output |
| 5 20 50 100 10 75 |
100 75 50 |
It seems trivial, but it is not that easy… The problem is that the reverse sorting in Java is a little more complicated, e.g. Java does not support it as the normal one. After some research, I simply decided to do a small cheat, giving me 100% of the points. The cheat consists of the fact, that I actually do not need reverse sorting, as far as I already know that the highest number is at the last position – thus, my solution is quite unexpected … But it worked OK, so I was happy with it. A second difficult task at the solution was the fact that we should be able to sort decimal numbers as well. I do not know why, but using BigDecimal was a little strange for me, I was trying to use some float types, but things did not work out so well. Here is my working code:
import java.util.*;
import java.math.*;
public class ThreeLargestNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Integer n = Integer.parseInt(scanner.nextLine());
BigDecimal[] array = new BigDecimal[n];
for (int i = 0; i < array.length; i++) {
String input = scanner.nextLine();
array[i] = new BigDecimal(input);
}
Arrays.sort(array);
if (n >= 3) {
System.out.println(array[n-1].toPlainString());
System.out.println(array[n-2].toPlainString());
System.out.println(array[n-3].toPlainString());
}
else if (n == 2) {
System.out.println(array[n-1].toPlainString());
System.out.println(array[n-2].toPlainString());
}
else {
System.out.println(array[n-1].toPlainString());
}
}
}
From the other part, the original code is not so cheaty, thus they make it a little useful for many purposes. What they do different, is that they introduce a second loop, that actually prints the last three positions of the array. The idea for putting two conditions in a for loop was something that I really have not seen (yup!) and something definitely useful. Here is how it looks like:
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
public class ThreeLargestNumbers {
public static void main(String[] args) {
Locale.setDefault(Locale.ROOT);
Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.nextLine();
BigDecimal[] nums = new BigDecimal[n];
for (int i = 0; i < nums.length; i++) {
String num = input.nextLine();
nums[i] = new BigDecimal(num);
}
Arrays.sort(nums);
int count = 3;
for (int i = nums.length-1; i >= 0 && count > 0; i--, count--) {
System.out.println(nums[i].toPlainString());
}
}
}
Enjoy both codes 😀
