1281.整数的各位积和之差
链接:1281.整数的各位积和之差
难度:Easy
标签:数学
简介:给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
题解 1 - cpp
- 编辑时间:2023-08-09
- 内存消耗:5.7MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
int subtractProductAndSum(int n) {
int num1 = 1, num2 = 0;
while (n) {
num1 *= n % 10;
num2 += n % 10;
n /= 10;
}
return num1 - num2;
}
};
题解 2 - rust
- 编辑时间:2023-08-09
- 内存消耗:2MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
pub fn subtract_product_and_sum(mut n: i32) -> i32 {
let mut num1 = 1;
let mut num2 = 0;
while n != 0 {
num1 *= n % 10;
num2 += n % 10;
n /= 10;
}
num1 - num2
}
}
题解 3 - python
- 编辑时间:2023-08-09
- 执行用时:44ms
- 内存消耗:16.1MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
def subtractProductAndSum(self, n: int) -> int:
num1 = 1
num2 = 0
while n:
num1 *= n % 10
num2 += n % 10
n //= 10
return num1 - num2