【算法】1281. 整数的各位积和之差(javacc++pythongorust)

【算法】1281. 整数的各位积和之差(javacc++pythongorust),第1张

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

文章目录
  • 1281. 整数的各位积和之差:
  • 样例 1:
  • 样例 2:
  • 提示:
  • 分析
  • 题解
    • java
    • c
    • c++
    • python
    • go
    • rust
  • 原题传送门:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/


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 <= 1 0 5 10^5 105

分析
  • 面对这道算法题目,我陷入了沉思。
  • 我实在想不出有什么妙法,只能按题意去做了。
  • 如果说有点什么需要注意的点的话,可能就是怎么取出每一位数。
  • 对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://le-yi.blog.csdn.net/ 博客原创~


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5670084.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存