[LeetCode] 1281. 整数的各位积和之差

1 题目描述

给你一个整数 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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2 解题思路

我们每次通过取模运算得到 n 的最后一位,依次进行乘法和加法运算,最后将得到的积 mul 以及和 add 相减即可得到答案。

复杂度分析
时间复杂度:O(logN)。整数N 的位数为 在这里插入图片描述,根据换底公式,它和时间复杂度中常用的以 2 为底的 log 只相差一个常数,因此可以表示为O(logN)。

空间复杂度:O(1)。

作者:LeetCode
链接:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/solution/zheng-shu-de-ge-wei-ji-he-zhi-chai-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

3 解决代码

  • java代码
class Solution {
    public int subtractProductAndSum(int n) {
        int mul = 1, add = 0;
        while(n != 0){
            int count = n%10;
            n = n/10;
            mul *= count;
            add += count;    
        }
        return mul - add;
    }
}
  • python 代码
class Solution(object):
    def subtractProductAndSum(self, n):
        """
        :type n: int
        :rtype: int
        """
        mul,add =1, 0
        while n != 0:
            count = n %10
            n = n /10
            mul *= count
            add += count
        return mul - add

你可能感兴趣的:(力扣LeetCode)