数组剔除元素后的乘积

描述

给定一个整数数组A。
定义B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], 计算B的时候请不要使用除法。请输出B。

 

样例

样例 1

输入: A = [1, 2, 3]
输出: [6, 3, 2]
解析:B[0] = A[1] * A[2] = 6; B[1] = A[0] * A[2] = 3; B[2] = A[0] * A[1] = 2

样例 2

输入: A = [2, 4, 6]
输出: [24, 12, 8]

话不多说,很简单,直接上代码 

import java.util.ArrayList;
import java.util.List;

public class ProductExcludeItself {
    public static void main(String[] args) {
        List<Integer> list=new ArrayList<>();
        list.add(2);
        list.add(4);
        list.add(6);
        List<Long> result=new ArrayList<>();
        result=productExcludeItself(list);
        for (int i = 0; i <result.size() ; i++) {
            System.out.print(result.get(i)+" ");
        }
    }
    public static List<Long> productExcludeItself(List<Integer> nums) {
        // write your code here
        List<Long> result=new ArrayList<>();
        for (int i = 0; i <nums.size() ; i++) {
            long temp=1;
            for (int j = 0; j <nums.size() ; j++) {
                if (i==j){
                    continue;
                }else {
                    temp = temp * nums.get(j);
                }
            }
            result.add(temp);
        }
        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值