LEETCODE 1281. Subtract the Product and Sum of Digits of an Integer 解题思路分析

题目大意:

整数的各位积和之差

给你一个整数 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

如果想查看本题目是哪家公司的面试题,请参考以下免费链接: https://leetcode.jp/problemdetail.php?id=1281

解题思路分析:

这道题很简单,只需要按照题意算出所有位的和与乘积,再相减即可。关在在于如何得到每一位上的数字。如果用字符串去一位一位的取效率很低,直接用数学方式操作整数n是最简单的方式。因为是10进制数,取最低位可以使用当前数与10的余数,比如123,最低位等于123%10=3。取完后将123除以10,变为:123/10=12,再按照之前的方式取出最低位,直到所有位都取完为止。

实现代码:

public int subtractProductAndSum(int n) {
    int product=1, sum=0; // 默认乘积为1,和为0
    while(n>0){ // 循环取每一位上的数字
        int digit = n % 10; // 当前位
        product*=digit; // 求乘积
        sum+=digit; // 求和
        n/=10; // 当前数除以10
    }
    return product-sum;
}

本题解法执行时间为0ms。

Runtime: 0 ms, faster than 100.00% of Java online submissions for Subtract the Product and Sum of Digits of an Integer.

Memory Usage: 32.9 MB, less than 100.00% of Java online submissions for Subtract the Product and Sum of Digits of an Integer.

本网站文章均为原创内容,并可随意转载,但请标明本文链接
如有任何疑问可在文章底部留言。为了防止恶意评论,本博客现已开启留言审核功能。但是博主会在后台第一时间看到您的留言,并会在第一时间对您的留言进行回复!欢迎交流!
本文链接: https://leetcode.jp/leetcode-1281-subtract-the-product-and-sum-of-digits-of-an-integer-解题思路分析/
此条目发表在leetcode分类目录,贴了, , 标签。将固定链接加入收藏夹。

发表评论

您的电子邮箱地址不会被公开。