Subtract the Product and Sum of Digits of an Integer
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves processing the digits of a number to calculate both the product of
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves processing the digits of a number to calculate both the product of its digits and the sum of its digits, and then returning the difference between the two. My first thought was to break the number down into its individual digits by repeatedly taking the modulus of the number with 10 (`n % 10`) and accumulating both the product and sum. The product is initialized as 1 (since multiplying by 0 would always yield 0), and the sum starts at 0.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialization**: Initialize two variables: `product` to 1 (to start multiplying digits) and `sum` to 0 (to accumulate the sum of digits).\n2. **Extract digits**: Use a `while` loop to repeatedly extract the last digit of the number using `n % 10`.\n3. **Update product and sum**: For each digit:\n   - Multiply it with the current product.\n   - Add it to the current sum.\n4. **Reduce the number**: After processing the digit, divide `n` by 10 to remove the last digit (`n = n / 10`).\n5. **Return result**: After all digits have been processed, return the difference between the product and the sum.\n\n# Complexity\n- **Time complexity**:  \n  The time complexity is (O(d)), where (d) is the number of digits in the input number `n`. Since the number of digits is proportional to ( log_{10}(n) ), we can say the time complexity is (O(log n)).\n\n- **Space complexity**:  \n  The space complexity is (O(1)) because the algorithm only uses a constant amount of extra space for variables (`product`, `sum`, `temp`, and `n`).\n\n# Code\n```java []\nclass Solution {\n    public int subtractProductAndSum(int n) {\n        int product = 1;\n        int sum = 0;\n        while (n > 0) {\n            int temp = n % 10;\n            product = product * temp;\n            sum = sum + temp;\n            n = n / 10;\n        }\n        return product - sum;\n    }\n}\n```
['Math', 'Java']