leetcode链接:1281. 整数的各位积和之差
题目分析

方案一
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public int subtractProductAndSum(int n) { int sum = 0, mul = 1, i;
for (; n > 0;) { i = n % 10; sum += i; mul *= i; n = n / 10; } return mul - sum; } }
|
结果
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:38.3 MB,击败了59.11% 的Java用户
分析
时间复杂度:
O( m ) 数字n的位数
空间复杂度:
O( 1 )
官方题解
https://leetcode.cn/problems/subtract-the-product-and-sum-of-digits-of-an-integer/solution/zheng-shu-de-ge-wei-ji-he-zhi-chai-by-leetcode-sol/

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public int subtractProductAndSum(int n) { int m = 1, s = 0; while (n != 0) { int x = n % 10; n /= 10; m *= x; s += x; } return m - s; } }
作者:LeetCode-Solution 链接:https: 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|
