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 |
<strong>Input:</strong> n = 234 <strong>Output:</strong> 15 <strong>Explanation:</strong> 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 |
<strong>Input:</strong> n = 4421 <strong>Output:</strong> 21 <strong>Explanation: </strong>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
Solution: Simulation
Time complexity: O(logn)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua class Solution { public: int subtractProductAndSum(int n) { int p = 1; int s = 0; while (n) { const int d = n % 10; p *= d; s += d; n /= 10; } return p - s; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment