我正在尝试编写一种方法,查找在第一个位置和最后一个位置之间有多少个奇数。该方法接受一个数组,然后两个int
s用于低位和高位。该方法需要递归地进行。这是我到目前为止所拥有的。这是方法调用和int数组。我的输出为1,但答案应为2。
int array [] = {5, 2, 5, 6, 3, 1};
int n = countOddsInRange(array, 1, 4)
public static int countOddsInRange(int [] a, int first, int last)
{
int count = 0;
if(first <= last)
{
countOddsInRange(a, a[first + 1], a[last]);
if(a[first] % 2 == 0)
{
count++;
}
}
return count;
}
答案 0 :(得分:5)
您的代码中存在一些错误:
if(a[first] % 2 != 0)
count+=countOddsInRange(a, first + 1, last)
总结:
public static int countOddsInRange(int [] a, int first, int last)
{
int count = 0;
if(first <= last)
{
count+=countOddsInRange(a, first + 1, last);
if(a[first] % 2 != 0)
{
count++;
}
}
return count;
}
答案 1 :(得分:0)
您的功能应如下所示:
public static int countOddNumber(int [] a, int first, int last){
return countOddNumber(a, first, last, 0);
}
public static int countOddNumber(int [] a, int first, int last, int count){
//in recursive function start with termination test.
if (first == last){
return count + isOdd(a[first]);
}
else{
return countOddNumber(a, first+1, last, count) + isOdd(a[first]);
}
}
public static int isOdd(int number){
if(number%2 == 0){return 1;}
else{return 0}
}
你还应该添加一个测试来检查first是否小于last,以避免无限循环;)
PS:过滤元素,其mod(element,2)= 0,然后获取集合的大小。该方法也使用功能样式,并使用新的Java8功能。并且可能要快得多。
答案 2 :(得分:0)
public class CountOddsInRange {
public static void main(String[] args) {
int array[] = {5, 2, 5, 6, 3, 1};
int n = countOddsInRange(array, 0, array.length - 1, 0);
System.out.println("No of odds is " + n);
}
public static int countOddsInRange(int[] a, int first, int last, int count) {
if (first <= last) {
if (a[first] % 2 != 0) {
count++;
}
return countOddsInRange(a, first + 1, last, count);
}
return count;
}
}
答案 3 :(得分:0)
public class CountOddsInRange {
public static void main(String[] args) {
int array[] = {5, 2, 5, 6, 3, 1};
int n = countOddsInRange(array, 0, array.length - 1);
System.out.println("No of odds is " + n);
}
public static int countOddsInRange(int [] a, int first, int last)
{
int count = 0;
if(first <= last)
{
count+=countOddsInRange(a, first + 1, last);
if(a[first] % 2 != 0)
{
count++;
}
}
return count;
}
}