comments | difficulty | edit_url | rating | source | tags | |
---|---|---|---|---|---|---|
true |
简单 |
1141 |
第 166 场周赛 Q1 |
|
给你一个整数 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:
nums = list(map(int, str(n)))
return prod(nums) - sum(nums)
class Solution {
public int subtractProductAndSum(int n) {
int x = 1, y = 0;
for (; n > 0; n /= 10) {
int v = n % 10;
x *= v;
y += v;
}
return x - y;
}
}
class Solution {
public:
int subtractProductAndSum(int n) {
int x = 1, y = 0;
for (; n; n /= 10) {
int v = n % 10;
x *= v;
y += v;
}
return x - y;
}
};
func subtractProductAndSum(n int) int {
x, y := 1, 0
for ; n > 0; n /= 10 {
v := n % 10
x *= v
y += v
}
return x - y
}
function subtractProductAndSum(n: number): number {
let [x, y] = [1, 0];
for (; n > 0; n = Math.floor(n / 10)) {
const v = n % 10;
x *= v;
y += v;
}
return x - y;
}
impl Solution {
pub fn subtract_product_and_sum(mut n: i32) -> i32 {
let mut x = 1;
let mut y = 0;
while n != 0 {
let v = n % 10;
n /= 10;
x *= v;
y += v;
}
x - y
}
}
public class Solution {
public int SubtractProductAndSum(int n) {
int x = 1;
int y = 0;
for (; n > 0; n /= 10) {
int v = n % 10;
x *= v;
y += v;
}
return x - y;
}
}
int subtractProductAndSum(int n) {
int x = 1;
int y = 0;
for (; n > 0; n /= 10) {
int v = n % 10;
x *= v;
y += v;
}
return x - y;
}