题目
不包含本位置值的累乘数组
java代码
package com.lizhouwei.chapter8;
/**
* @Description: 不包含本位置值的累乘数组
* @Author: lizhouwei
* @CreateDate: 2018/5/9 21:11
* @Modify by:
* @ModifyDate:
*/
public class Chapter8_22 {
public int[] product(int[] arr) {
int[] res = new int[arr.length];
int product = 1;
for (int i = 0; i < arr.length; i++) {
res[i] = product * arr[i];
product = product * arr[i];
}
product = 1;
for (int i = arr.length - 1; i > 0; i--) {
res[i] = res[i - 1] * product;
product = product * arr[i];
}
res[0] = product;
return res;
}
//测试
public static void main(String[] args) {
Chapter8_22 chapter = new Chapter8_22();
int[] arr = {2, 3, 1, 4};
int[] res = chapter.product(arr);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
}
}
结果