// 1281. 整数的各位积和之差
// 给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
// 示例 1:
// 输入:n = 234
// 输出:15
// 解释:
// 各位数之积 = 2 * 3 * 4 = 24
// 各位数之和 = 2 + 3 + 4 = 9
// 结果 = 24 - 9 = 15
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer
// 我的思路,写一个function得到拆分后的list,再进行计算。用到了String,内存占用高,效率低。
public int subtractProductAndSum(int n) {
//算法要判断特殊条件
List<Integer> i = getInt(n);
int a = 1, b = 0;
for (Integer integer : i) {
a = a * integer;
b = b + integer;
}
return a - b;
}
//官方解题思路
public int subtrackProductAndSum2(int n) {
int add = 0, mul = 1;
while (n > 0) {
int digit = n % 10;
n /= 10;
add += digit;
mul *= digit;
}
return mul - add;
}
public List<Integer> getInt(int n) {
List<Integer> i = new ArrayList<Integer>();
int t = 0;
String str = "" + n;
for (int x = 0; x < str.length(); x++) {
char a = str.charAt(x);
i.add(a - '0');
}
return i;
}
leetcode-1281. 整数的各位积和之差
最新推荐文章于 2024-09-23 11:27:55 发布