[LeetCode] 238. Product of Array Except Self(Kotlin)
풀이
class Solution {
fun productExceptSelf(nums: IntArray): IntArray {
val zeroCount = nums.count{it == 0}
if(zeroCount > 1){
return IntArray(nums.size){0}
}
val ans = mutableListOf<Int>()
var totalProduct = 1L
nums.forEach{ num ->
if(num != 0) totalProduct *= num.toLong()
}
println(totalProduct)
if(zeroCount == 1){
nums.forEach{ num ->
if(num == 0) ans.add(totalProduct.toInt())
else ans.add(0)
}
}
else{
nums.forEach{ num ->
ans.add((totalProduct/num).toInt())
}
}
return ans.toIntArray()
}
}