I am trying to solve the Sherlock and The Beast HackerRank challenge. Most tests timeout, however when I try a custom stretch test case (T = 20 and all N = 100000), it returns successfully, so I'm not sure what the problem is.
The idea of the algorithm is that I find the number of possible combinations of threes and fives for a given number of digits, then I treat threes as zeros and fives as ones, in order to process a binary number. So for N = 3 digits, we have 8 combinations (from 7 to 0) which in binary terms is (descending) from 111 to 000, which in three and five terms is from 555 to 333.
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int testCases = in.nextInt();
for(int i = 0; i < testCases; i++){
System.out.println( solve( in.nextInt() ) );
}
}
private static String solve(int n){
long combos = (long)Math.pow(2,n);
for(long i = combos-1; i>=0; i--){
String toStr = String.format("%"+n+"s", Long.toBinaryString(i)).replace(' ', '0');
String modified = toStr.replace("0","3").replace("1","5");
int threes =0;
for( int j=0; j<modified.length(); j++ ) {
if( modified.charAt(j) == '3' ) {
threes++;
}
}
if(threes%5==0) {
int fives =0;
for( int k=0; k<modified.length(); k++ ) {
if( modified.charAt(k) == '5' ) {
fives++;
}
}
if(fives%3==0) return modified;
}
}
return "-1";
}
}
n=100000
? It quite clearly can't give correct results for any value ofn
greater than63
, so I think you need to start by checking your test wrapper. \$\endgroup\$