Skip to content

Instantly share code, notes, and snippets.

@tioback
Last active June 12, 2017 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tioback/8f4868a2a170da89351a39d0d6e23134 to your computer and use it in GitHub Desktop.
Save tioback/8f4868a2a170da89351a39d0d6e23134 to your computer and use it in GitHub Desktop.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
// https://www.hackerrank.com/challenges/a-very-special-multiple
public class AVerySpecialMultiple {
private static Pattern PATTERN = Pattern.compile("^(4+)(0*)$");
private static final String test1 = "3\n" +
"4\n" +
"5\n" +
"80";
private static final String test2 = "5\n" +
"62\n" +
"67\n" +
"20\n" +
"63\n" +
"81";
private static final String test3 = "8\n" +
"4\n" +
"5\n" +
"80\n" +
"62\n" +
"67\n" +
"20\n" +
"63\n" +
"81";
public static void main(String[] args) {
// try (Scanner sc = new Scanner(System.in)) {
try (Scanner sc = new Scanner(test3)) {
int t = sc.nextInt();
while (t-- > 0) {
long X = sc.nextLong();
BigDecimal x = new BigDecimal(X);
BigDecimal y = geraNumeros(x);
if (y == null) {
System.out.println("Illegal value for X");
continue;
}
BigDecimal multi = x.multiply(y);
int a = multi.toString().replaceAll("0", "").length();
int b = multi.toString().replaceAll("4", "").length();
int _2timesAplusB = (2 * a) + b;
System.out.printf("X [%s] * Y [%s] = MULTI [%s] (0s: %d, 4s: %d) | (2 * a) + b = %d\n", x.toString(), y.toString(), multi.toString(), a, b, _2timesAplusB);
//System.out.println(_2timesAplusB);
}
}
}
private static BigDecimal geraNumeros(BigDecimal x) {
List<BigDecimal> numeros = new ArrayList<>();
BigDecimal FOUR = new BigDecimal(4);
if (check(x, FOUR)) {
return FOUR.divide(x, BigDecimal.ROUND_HALF_EVEN);
}
numeros.add(FOUR);
int i = 0, j = 0;
while (i < Integer.MAX_VALUE) {
BigDecimal result = numeros.get(j++).multiply(BigDecimal.TEN);
if (check(x, result)) {
return result.divide(x, BigDecimal.ROUND_HALF_EVEN);
}
numeros.add(result);
i++;
result = result.add(FOUR);
if (matches(result)) {
if (check(x, result)) {
return result.divide(x, BigDecimal.ROUND_HALF_EVEN);
}
numeros.add(result);
i++;
}
}
return null;
}
private static boolean check(BigDecimal x, BigDecimal result) {
return result.remainder(x).equals(BigDecimal.ZERO);
}
private static boolean matches(BigDecimal multi) {
return PATTERN.matcher(multi.toString()).matches();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment