gpt4 book ai didi

java - 数组中等于 N 的连续数的所有可能的和

转载 作者:行者123 更新时间:2023-11-30 03:06:18 25 4
gpt4 key购买 nike

我试图从数组中的连续元素中找到所有可能的和,这些元素的总和达到特定的数字。例如:-

a[] = {4,7,2,1,3,8,5}; and N = 13,
Output = {4,7,2},{7,2,1,3},{8,5}

这是我的代码 -

 int low = 0;
int high = 0;
int sum = a[0];
while(high < a.length) {
if(sum < 13) {
high++;

if(high < a.length) {
sum+= a[high];

}
} else if(sum > 13) {
sum-=a[low];
low++;

}
if(sum == 13) {
for(int i=low;i<=high;i++) {
System.out.println(a[i]);
}
System.out.println("new ");
low++;
high++;
sum = 0;
//return;
}
}

但输出仅返回一组 {4,7,2} 。我无法打印其他套装。谁能帮我解决这个问题

最佳答案

找到第一个序列后,您没有正确重置变量:

        if(sum == 13) {
for(int i=low;i<=high;i++) {
System.out.println(a[i]);
}
System.out.println("new ");
low++;
high++; // change to high = low; // since you want your loop to test
// sequences that start at the new (post incremented) low
sum = 0; // change to sum = a[low]; // since the initial sum is the value of
// the first element in the new sequence
}

关于java - 数组中等于 N 的连续数的所有可能的和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34702799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com