patternjavaMinor
"Sherlock and the Beast" challenge in Java
Viewed 0 times
thechallengejavasherlockandbeast
Problem
I have been trying to solve the following problem on hackerrank.com, but when I submit the code it shows unsuccessful submission due to timeout. Can anyone help me out?
Sherlock and the Beast
Sherlock and the Beast
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int a[] = new int[t];
// reading test cases
for( int i=0; i= 0; x--){
for( int y = testy; y >= 0; y--){
if( ( x==0 && y== 0 ) ){
System.out.println("-1");
break1 = true;
break;
}
else if ( n % (3*x+5*y) == 0){
System.out.println( getdecentString(x, y) );
break1 = true;
break;
}
}
if ( break1 == true)
break;
}
}
}
// function to generate decentString
static String getdecentString(int x, int y){
String decentString = "";
x = 3*x;
y = 5*y;
for( int j=1; j <= x; j++)
decentString = decentString + "5";
for( int k=1; k <= y; k++)
decentString = decentString + "3";
return decentString;
}
}Solution
As Robert pointed out, your code spends a lot of time in
getdecentString. A faster way to generate Strings would be to use the StringBuilder class, e.g.:StringBuilder decentString = new StringBuilder();
...
for ( int j = 1; j <= x; j++ )
{
decentString.append( "5" );
}
...
return decentString.toString();Code Snippets
StringBuilder decentString = new StringBuilder();
...
for ( int j = 1; j <= x; j++ )
{
decentString.append( "5" );
}
...
return decentString.toString();Context
StackExchange Code Review Q#101964, answer score: 5
Revisions (0)
No revisions yet.