Subtract the Product and Sum of Digits of an Integer

  • 时间:2020-09-15 16:10:27
  • 分类:网络文摘
  • 阅读:75 次

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Example 1:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 – 9 = 15

Example 2:
Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 – 11 = 21

Constraints:
1 <= n <= 10^5

Hints:
How to compute all digits of the number?
Use modulus operator (%) to compute the last digit.
Generalise modulus operator idea to compute all digits.

leetcode-debugger Subtract the Product and Sum of Digits of an Integer algorithms c / c++ math programming languages python

leetcode-debugger

To get the digits of a integer, we can iteratedly divide the integer by ten, and retrieve the right-most digit by using modulous operator (%). The time complexity is O(lgN).

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
    int subtractProductAndSum(int n) {
        int sum = 0;
        int product = 1;
        while (n > 0) {
            sum += n % 10;
            product *= n % 10;
            n /= 10;
        }
        return product - sum;
    }
};
class Solution {
public:
    int subtractProductAndSum(int n) {
        int sum = 0;
        int product = 1;
        while (n > 0) {
            sum += n % 10;
            product *= n % 10;
            n /= 10;
        }
        return product - sum;
    }
};

The C++ code above requires O(1) constant space. And in Python, you could convert the integer into string, join them with a space, then split them into array of digit strings, finally convert them into list of digits by using the map function.

1
2
3
4
5
6
7
from operator import mul
from functools import reduce
 
class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        temp = list(map(int, ' '.join(str(n)).split()))
        return reduce(mul, temp, 1) - sum(temp)
from operator import mul
from functools import reduce

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        temp = list(map(int, ' '.join(str(n)).split()))
        return reduce(mul, temp, 1) - sum(temp)

Then, we can compute the produce by using the reduce function, with the mul operator. The sum of digits can be just obtained via the sum() function.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
数学题:一个底面半径是6厘米的圆柱形玻璃器皿里装有一部分水  数学题:已知点D、E、F分别是BC、AD、BE上的中点  数学题:21个同学来取水果  数学题:四一班买了30只红气球和黄气球装点教室  数学题:三组都参加的有多少人  数学题:一个梯形,如果底延长6厘米  数学题:五星村计划由10名工人16天修一条道路  奥数题:至少有几名同学所拿的球种类是一致的  奥数题:在离山顶600m处两人相遇  数学题:至少要到什么时候才能再次同时发车 
评论列表
添加评论