编程练习
题目:给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…A[i-1]A[i+1]…A[n-1]。不能使用除法。
思路:很简单的一道题,只需要捋清楚思路即可,规律即是每次从A中去除第i个元素,然后将剩下的所有元素全部乘起来得到的值作为b的第i个元素。用嵌套for循环即可解决。
java代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34public class Multiply {
public static int[] multiply(int[] A) {
int [] b=new int [A.length];
//将A中的数字全部放入list中方便后续操作
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i:A) {
list.add(i);
}
for(int i=0;i<A.length;i++) {
//临时的tmp用来存储list的复制,以便下面每次移除元素后下次循环用的还是list中的全部数据
ArrayList<Integer> tmp=new ArrayList<Integer>();
for(int c:list) {
tmp.add(c);
}
tmp.remove(i);
int r=1;
for(int j=0;j<tmp.size();j++) {
r*=tmp.get(j);
}
b[i]=r;
}
return b;
}
public static void main(String[] args) {
int [] arr= {};
int [] b=multiply(arr);
for(int i:b) {
System.out.println(i);
}
}
}