問題
原文
Given an integer number
n
, return the difference between the product of its digits and the sum of its digits.
Example 1:
123456 Input: n = 234Output: 15Explanation:Product of digits = 2 * 3 * 4 = 24Sum of digits = 2 + 3 + 4 = 9Result = 24 - 9 = 15Example 2:
123456 Input: n = 4421Output: 21Explanation:Product of digits = 4 * 4 * 2 * 1 = 32Sum of digits = 4 + 4 + 2 + 1 = 11Result = 32 - 11 = 21
Constraints:
1 <= n <= 10^5
内容
整数nが与えられるので、各桁の積と和の差を返してください。
制約からnは最大10^5の桁数があるので、時間計算量O(n)の解法では10^5の計算量に収まる。
※正しくない可能性があります。
解答
解答1:Python, brute force
1 2 3 4 5 6 7 8 9 10 11 |
class Solution: def subtractProductAndSum(self, n: int) -> int: n = str(n) products_of_digits = 1 sum_of_digits = 0 for i in range(len(n)): products_of_digits *= int(n[i]) sum_of_digits += int(n[i]) return products_of_digits - sum_of_digits |
最初にnを文字列に変換しているので、for文の内部で毎回intに変換しているのは改善の余地がありそう。
解答2:
メモ・参考・感想
コメント