【LetMeFly】1281.整數的各位積和之差
力扣題目鏈接:https://leetcode.cn/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
給你一個整數?n
,請你幫忙計算并返回該整數「各位數字之積」與「各位數字之和」的差。
?
示例 1:
輸入:n = 234 輸出:15 解釋: 各位數之積 = 2 * 3 * 4 = 24 各位數之和 = 2 + 3 + 4 = 9 結果 = 24 - 9 = 15
示例 2:
輸入:n = 4421 輸出:21 解釋: 各位數之積 = 4 * 4 * 2 * 1 = 32 各位數之和 = 4 + 4 + 2 + 1 = 11 結果 = 32 - 11 = 21
?
提示:
1 <= n <= 10^5
方法一:取出每一位
這道題主要在考察如何取出一個整數的每一位。當然,可以使用內置函數將整數轉為字符串,再遍歷字符串的每一位。但是還可以:
在整數 n n n不為零時:
- 取出 n % 10 n \% 10 n%10來做運算
- n / = 10 n /= 10 n/=10
這樣就取出整數的每一位了。
- 時間復雜度 O ( log ? 10 n ) O(\log_{10}n) O(log10?n)
- 空間復雜度 O ( 1 ) O(1) O(1)
AC代碼
C++
class Solution {
public:int subtractProductAndSum(int n) {int mul = 1, cnt = 0;while (n) {mul *= n % 10;cnt += n % 10;n /= 10;}return mul - cnt;}
};
Python
class Solution:def subtractProductAndSum(self, n: int) -> int:mul, cnt = 1, 0while n:mul *= n % 10cnt += n % 10n //= 10return mul - cnt
同步發文于CSDN,原創不易,轉載請附上原文鏈接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/132179859