Sherlock and The Beast

Sherlock and The Beast is a HackerRank challenge. The name is good and the description quite amusing. Please take a look at it at the following URL: https://www.hackerrank.com/challenges/sherlock-and-the-beast?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign

A screen capture, using the sample input from the challenge, from the console of the Eclipse IDE follows:

4

1

3

5

11

-1

555

33333

55555533333

The output matches the sample output for the challenge.

The recommended help suggested Div Mod and Greedy Technique. I have not read the test yet; will do it after lunch.

My solution in Java follows:

import java.util.Scanner;

public class Solution {

/**

* display the number

*/

static void printNumber(int numOf5s, int numOf3s) {

for ( ; numOf5s > 0; numOf5s–) {

System.out.print(“5”);

}

for ( ; numOf3s > 0; numOf3s–) {

System.out.print(“3”);

}

System.out.println();

}

/**

* print the largest decent number with n digits

*/

static void decentNumber(int n) {

// **** starting counts ****

int numOf5s   = (n / 3) * 3;

int numOf3s   = 0;

// **** ****

while (true) {

// **** number of 5s divisible by 3 && number of 3s divisible by 5 ****

if (((numOf5s % 3)         == 0) &&

((numOf3s % 5)             == 0) &&

((numOf5s + numOf3s) == n)) {

printNumber(numOf5s, numOf3s);

return;

}

// **** decrement number of 5s (by 1 set == 3) ****

if (numOf5s + numOf3s >= n) {

numOf5s -= 3;

}

// **** increment number of 3s (by 1 set == 5) ****

if (numOf5s + numOf3s < n) {

numOf3s += 5;

}

// **** check if there is no viable solution ****

if (numOf5s < 0) {

System.out.println(“-1”);

return;

}

}

}

/**

* test code

* @param args

*/

public static void main(String[] args) {

Scanner in   = new Scanner(System.in);

int t              = in.nextInt();

for(int a0 = 0; a0 < t; a0++){

int n = in.nextInt();

decentNumber(n);

}

in.close();

}

}

This challenge was ranked easy.

If you have comments or questions regarding this or any other post in this blog, please do not hesitate and send me a message. I will keep your name private unless you state otherwise.

John

John.canessa@gmail.com

Follow me on Twitter: @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *