Skip to content

Latest commit

 

History

History
139 lines (108 loc) · 2.44 KB

File metadata and controls

139 lines (108 loc) · 2.44 KB

English Version

题目描述

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

解法

Python3

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        s, p = 0, 1
        while n:
            t = n % 10
            n //= 10
            s += t
            p *= t
        return p - s

Java

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

C++

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

Go

func subtractProductAndSum(n int) int {
	s, p := 0, 1
	for n != 0 {
		t := n % 10
		n /= 10
		s += t
		p *= t
	}
	return p - s
}

Rust

impl Solution {
    pub fn subtract_product_and_sum(mut n: i32) -> i32 {
        let mut mul = 1;
        let mut sum = 0;
        while n != 0 {
            let num = n % 10;
            n /= 10;
            mul *= num;
            sum += num;
        }
        mul - sum
    }
}

...