carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1281:整数的各位积和之差(subtract-the-product-and-sum-of-digits-of-an-integer) #200

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

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

提示:

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/subtract-the-product-and-sum-of-digits-of-an-integer

carloscn commented 1 year ago

问题分析

pub fn subtract_product_and_sum(n: i32) -> i32
{
    if n < 1 {
        return 0;
    }

    let mut product:i32 = 1;
    let mut sum:i32 = 0;
    let mut nd:i32 = n;

    while nd != 0 {
        let e:i32 = nd % 10;
        product *= e;
        sum += e;
        nd /= 10;
    }

    return product - sum;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/553152 https://github.com/carloscn/structstudy/commit/39277eff1871ec3619d310ef2cbdd657242ffacc