1281. 整数的各位积和之差(java / c / c++ / python / go / rust)

416 阅读1分钟

「这是我参与2022首次更文挑战的第5天,活动详情查看:2022首次更文挑战」。


1281. 整数的各位积和之差:

给你一个整数 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 <= 10510^5

分析

  • 面对这道算法题目,我陷入了沉思。
  • 我实在想不出有什么妙法,只能按题意去做了。
  • 如果说有点什么需要注意的点的话,可能就是怎么取出每一位数。
  • 对10取余数是常规做法。
  • 不知道有么有可能,数学上能有什么高速解法。

题解

java

class Solution {
    public int subtractProductAndSum(int n) {
        int product = 1;
        int sum     = 0;

        while (n > 0) {
            int digit = n % 10;
            product *= digit;
            sum += digit;
            n /= 10;
        }

        return product - sum;
    }
}

c

int subtractProductAndSum(int n){
    int product = 1;
    int sum     = 0;

    while (n > 0) {
        int digit = n % 10;
        product *= digit;
        sum += digit;
        n /= 10;
    }

    return product - sum;
}

c++

class Solution {
public:
    int subtractProductAndSum(int n) {
        int product = 1;
        int sum     = 0;

        while (n > 0) {
            int digit = n % 10;
            product *= digit;
            sum += digit;
            n /= 10;
        }

        return product - sum;
    }
};

python

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        p = 1
        s = 0

        while n > 0:
            digit = n % 10
            p *= digit
            s += digit
            n //= 10

        return p - s
        

go

func subtractProductAndSum(n int) int {
    product := 1
    sum := 0

    for n > 0 {
        digit := n % 10
        product *= digit
        sum += digit
        n /= 10
    }

    return product - sum
}

rust

impl Solution {
    pub fn subtract_product_and_sum(n: i32) -> i32 {
        let mut product = 1;
        let mut sum = 0;

        let mut n = n;
        while n > 0 {
            let digit = n % 10;
            product *= digit;
            sum += digit;
            n /= 10;
        }

        product - sum
    }
}

在这里插入图片描述


原题传送门:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/


非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~