LeetCode #1281 Subtract the Product and Sum of Digits of an Integer 整数的各位积和之差

1281 Subtract the Product and Sum of Digits of an Integer 整数的各位积和之差

Description:
Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Example:

Example 1:

Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15

Example 2:

Input: n = 4421
Output: 21
Explanation:
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

题目描述:
给你一个整数 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

思路:

用取模算出乘积和和即可
时间复杂度O(lgn), 空间复杂度O(1)

代码:
C++:

class Solution 
{
public:
    int subtractProductAndSum(int n) 
    {
        int product = 1, sum = 0;
        while (n)
        {
            product *= n % 10;
            sum += n % 10;
            n /= 10;
        }
        return product - sum;
    }
};

Java:

class Solution {
    public int subtractProductAndSum(int n) {
        int product = 1, sum = 0;
        while (n != 0) {
            product *= n % 10;
            sum += n % 10;
            n /= 10;
        }
        return product - sum;
    }
}

Python:

from functools import reduce
class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        return reduce(lambda x, y: x * y, [int(i) for i in str(n)]) - sum(int(i) for i in str(n))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一直身处岭南之地,很少感受四季分明的感觉,这次跟秋天撞了一下腰,跟随我一起感受秋韵之美…
    自在歌者阅读 380评论 0 2
  • 常用apk downloadhttps://apkpure.com/https://apkpure.com/cn?...
    jaqen_阅读 149评论 0 0
  • 如何对待反馈: 不确定的用法:native speaker怎么说,查英英搭配词典 先守/临摹,别着急创作。(写对一...
    guido_bxl阅读 393评论 0 1
  • 为何又开始焦躁不安了呢?因为老板要我去做一件比较为难的事情,为什么说为难呢?因为这个事情需要走人情,所以这是个很让...
    百荷清梦阅读 280评论 0 0

友情链接更多精彩内容