leetcode-1281. 整数的各位积和之差

//    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;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值