HackerRank : Week of Code 30 – Find the Minimum Number

By | March 14, 2017
Find the Minimum Number : Hackerrank

Jessica is learning to code and was recently introduced to the min function. This function compares two integers and returns the smaller one. This is what calling the function looks like when comparing two integers a and b:

min(a, b)

Jessica realizes that she can also find the smallest of three integers a, b,c  and if she puts the min  function inside of another min function:

min(a, min(b, c))

For four integers she can nest the functions once more:

min(a, min(b, min(c, d)))

Jessica is curious about the structure of these function calls and wants to see if she can write a program to construct a string that shows how n number of integers can be compared with nested min functions. Can you help Jessica write this program?

Input Format
The input contains a single integer (the number of integers n to be compared).
Output Format

Print the string on a single line. Integer in each the string should be written as ‘int’ and the string must accurately show how min  functions can be called to find the smallest of n integers.

Sample Input 0

2

Sample Output 0

min(int, int)

Explanation 0
With an input of  2 we only have two integers to compare. We don’t need to nest the min functions for our output because the min function can take two integers as input.
Sample Input 1

4

Sample Output 1

min(int, min(int, min(int, int)))

Solution

Its a pretty simple problem as well. You just need to play with the string to get the 
perfect output.
package weekOfCode30;

import java.util.Scanner;

public class FindTheMinimumNumber {

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		String str = "min(int, int)";
		StringBuilder sB = new StringBuilder(str);
		String appendStr = "min(int, ";
		String appendStrClose = ")";

		int n = scan.nextInt();
		for (int i = 2; i < n; i++) {
			sB.insert(0, appendStr);
			sB.insert(sB.length(), appendStrClose);
		}
		System.out.println(sB);

	}
}