给你一个整数 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
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
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;
}
}
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;
}
};
func subtractProductAndSum(n int) int {
s, p := 0, 1
for n != 0 {
t := n % 10
n /= 10
s += t
p *= t
}
return p - s
}
function subtractProductAndSum(n: number): number {
let p = 1;
let s = 0;
while (n) {
const num = n % 10;
n = Math.floor(n / 10);
p *= num;
s += num;
}
return p - s;
}
impl Solution {
pub fn subtract_product_and_sum(mut n: i32) -> i32 {
let mut p = 1;
let mut s = 0;
while n != 0 {
let num = n % 10;
n /= 10;
p *= num;
s += num;
}
p - s
}
}
int subtractProductAndSum(int n) {
int p = 1;
int s = 0;
while (n) {
int num = n % 10;
n /= 10;
p *= num;
s += num;
}
return p - s;
}