Leetcode: 1281

less than 1 minute read

1281. Subtract the Product and Sum of Digits of an Integer

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

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

Constraints:

  • 1 <= n <= 10^5

Solution:

class Solution {
    public int subtractProductAndSum(int n) {
        
        //slow solution, just share for idea
//         //string a = String.valueOf(n);
//         String a = Integer.toString(n);
//         String[] array = a.split("");
        
//         int prodcut = 1, sum = 0;
//         for( String element : array){
//             prodcut *= Integer.parseInt(element);
//             sum += Integer.parseInt(element);
//         }
        
//         return prodcut - sum ;
        int product = 1, sum = 0;
        while( n > 0){
            product *= n%10;
            sum += n%10;
            n = n/10;
        }
        return product - sum ;
    }
}

Updated: