【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(log10n)
- 空间复杂度 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