1 class Solution: 2 def subtractProductAndSum(self, n: int) -> int: 3 s = str(n) 4 mul,sums = 1, 0 5 for i in range(len(s)): 6 cur = int(s[i]) 7 mul *= cur 8 sums += cur 9 return mul - sums
一次循环,同时记录乘积与加和。循环结束,两值再相减。