找不到最小结果
输入:p = 1,r = 55,x = 5
输出:5 50
在迭代1到55之后,如果数字的总和= 5,则 可能的结果将为5,14,23,32,41,50 因此,输出是
我尝试按照代码执行的越来越大的结果,但是我从债券错误中获得了索引。 我认为这是因为if(sum == x)list.add(i);
在此列表中没有添加任何内容。
import java.util.*;
public class wiley{
static void find(int p,int r,int x){
List<Integer> list= new ArrayList<Integer>();
int sum=0,temp,rem;
for(int i=p;i<r;i++){
temp=p;
while(temp>0){
rem=temp%10;
sum+=rem;
temp=p/10;
}
if(sum==x) list.add(i);
sum=0;
}
int l=list.get(0);
int m=list.get(list.size()-1);
System.out.println(l);
System.out.println(m);
}
public static void main(String args[]){
int p=1;
int r=55;
int x=5;
find(p,r,x);
}
}
input: p=1,r=55,x=5
output:5
50
after iterating from 1 to 55,if the sum of digits =5 then
possible outcome will be 5,14,23,32,41,50
so the output is a smaller and greater outcome
I tried doing following code but I am getting index out of bond error.
I think it is because if(sum==x) list.add(i);
nothing is being added in this list.
import java.util.*;
public class wiley{
static void find(int p,int r,int x){
List<Integer> list= new ArrayList<Integer>();
int sum=0,temp,rem;
for(int i=p;i<r;i++){
temp=p;
while(temp>0){
rem=temp%10;
sum+=rem;
temp=p/10;
}
if(sum==x) list.add(i);
sum=0;
}
int l=list.get(0);
int m=list.get(list.size()-1);
System.out.println(l);
System.out.println(m);
}
public static void main(String args[]){
int p=1;
int r=55;
int x=5;
find(p,r,x);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是对的,您会收到错误,因为什么都没有添加到列表中。
这是因为在您的for循环中,您会迭代变量
i
,但您声明temp = p
。将此行更改为temp = i
。另外,您必须将
temp = p/10
更改为temp = temp/10
,就可以了。此外,您应该重写您的功能,以便即使列表中没有元素也没有异常。例如,您可以检查列表大小是否大于0,然后尝试访问其元素。
You are right, you get the error because nothing is added to the list.
This is because in your for loop, you iterate over the variable
i
, yet you declaretemp = p
. Change this line totemp = i
.Also, you have to change
temp=p/10
totemp=temp/10
and you're good to go.In addition, you should rewrite your function so that it does not throw an exception even if there is no element in the list. For example, you could check if the list size is greater than 0 and only then try to access its elements.