我有在Java返回类型的问题。该方案是关于不使用预定义的方法只是以递归方式经典算法分解以阵列5个chiffres的整数。我写的代码,并将其与递归很好地工作,但是当我赶上新数组从方法不会在所有情况下返回一个值,但它返回在一个单一的情况下,两个5 chiffres。我想实现这一目标是:
12345 >> [1][2][3][4][5]
但我的算法给了我这个:
12345 >> [0][12][123][1234][12345]
我想这个问题是在返回类型或声明的方法。
这是我的代码:
public class recursive {
static int[] Decompose (int[] tab , int pos,int num) //pos for position
{
if (pos == 0) //if it reach the last element of the table it stop
{
return tab;
}
else {
tab[pos]=num;
return Decompose(tab,pos-1,num/10); // if we didn't reach the end continue ...
}
}
public static void main(String[] args) {
int []t = new int[5];
int n=12345;//the number that i want to decompose
int pos=4;//the indicator of table position
t=Decompose(t,pos,n);
for (int i = 0; i < t.length; i++) {
System.out.println(t[i]);
}
}
}
它看起来像要存储在阵列中的每个位置上的单位数,所以你应该使用%
运营商来获得最后的数字:
...
tab[pos]=num%10;
return Decompose(tab,pos-1,num/10);
...
每次要指定数组的实际数量,这就是为什么你要在每个迭代的整数减一。您应该更改标签分配:
tab[pos] = num % 10;
另外,位置应达到的指标为0,所以更改检查:
if (pos < 0)