问题 :
鉴于a
和b
单位的两个权重,您可以使用给定权重以多少种方式获得d
单位的权重?任何给定的权重都可以使用任意次数(包括0次)。
示例:7只能通过使用2次和3次来实现 时间。 输入2 3 7(作为a,b,d按空间划分) 输出:1
我的程序在bluej上工作正常但在hackerearth在线编译器中没有。它说Runtime ERROR NZEC我的代码没有打印任何东西。继承我的计划:
import java.io.*;
public class WAYS
{
public static int process(String s)
{
s=s+" ";
int l=s.length();
String s1="";
int n[]=new int[3];
int j=0;
for(int i=0;i<l;i++)
{
char c=s.charAt(i);
if(c==' ')
{
n[j]=Integer.parseInt(s1);
j++;
s1="";
}
else
{
s1=s1+c;
}
}
int a=n[0];
int b=n[1];
int d=n[2];
int q=0;
for(int i=0;i<=d;i++)
{
int f=a*i;
for(int k=0;k<=d;k++)
{
int f1=b*k;
if(f+f1==d)
{
q++;
}
}
}
return q;
}
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of Test Cases");
int T=Integer.parseInt(br.readLine());
String s[]=new String[T];
int a[]=new int[T];
for(int i=0;i<T;i++)
{
System.out.print("("+(i+1)+")");
s[i]=br.readLine();
a[i]=process(s[i]);
}
System.out.println();
for(int i=0;i<T;i++)
{
System.out.println(a[i]);
}
}
}
你能告诉我哪里错了吗?
答案 0 :(得分:0)
您的错误很可能是因为您在内存变量中创建了太多内容。您必须在for循环之外创建变量并在循环内操作它。
EG:char c=s.charAt(i);
,int f=a*i;
和int f1=b*k;
答案 1 :(得分:0)
这可能是因为声明 -
n[j]=Integer.parseInt(s1); // since s1 here is ""
可能会在您的代码中导致NumberFormatException。
抛出以指示应用程序已尝试转换a 字符串到其中一个数字类型,但字符串没有 适当的格式。
重现的最小代码是 -
public static void main(String[] args) {
String str = "";
int n = Integer.parseInt(str);
}
虽然我不确定您所遵循的算法,但建议将一些数值作为字符串分配给s1
,如果那么转换是必须的。另外,请阅读 -
How to resolve java.lang.NumberFormatException: For input string: "N/A"?
答案 2 :(得分:0)
最后解决了这个问题。 使用JAVA时,总是在main方法中使用'String args []'和'throws Exception'。示例:public static void main(String args [])抛出异常{} 避免这种愚蠢的NZEC错误。如果这不起作用,请将main方法的返回类型设置为'int',并在关闭main方法之前返回0。 还要检查无限循环。