1281. Subtract the Product and Sum of Digits of an Integer

1281. Subtract the Product and Sum of Digits of an Integer

题目

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Example 1:

1
2
3
4
5
6
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15

Example 2:

1
2
3
4
5
6
Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21

Constraints:

  • 1 <= n <= 10^5

解题

我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def subtractProductAndSum(self, n):
"""
:type n: int
:rtype: int
"""
product = 1
sum = 0
for d in str(n).strip():
product *= int(d)
sum += int(d)
return product - sum

高赞代码:

1
2
3
4
class Solution(object):
def subtractProductAndSum(self, n):
A = map(int, str(n))
return reduce(operator.mul, A) - sum(A)

总结

  1. reduce函数
1
reduce(function, iterable[, initializer])
  • function – 函数,有两个参数
  • iterable – 可迭代对象
  • initializer – 可选,初始参数

reduce函数与map函数不同,它们都将可迭代对象的每一个元素带入第一个函数中,但是前者将结果累计,后者则是分别对每个元素作用。

  1. python标准库中的operator模块

operator模块提供了一系列与Python自带操作一样有效的函数。

operator模块是用c实现的,所以执行速度比python代码快。

当使用 map、filter、reduce这一类高阶函数时,operator模块中的函数可以替换一些lambda。例如:

1
reduce(lambda x,y:x*y, [1,2,3,4])

可以替换为:

1
reduce(operator.mul, [1,2,3,4])

References

python标准库之operator(运算符模块)