Subtract the Product and Sum of Digits of an Integer

Calculate of difference between the product of its digits and the sum of its digits.

Example 1:

Input: n=245
Output: 29 // i.e  sum=2+4+5=11, product=2*4*5=40, dif=product-sum=40-11=29
Approach

Java

public class SubtractProductAndSum {
    public static void main(String[] args) {
        int n = 245;
        int sub = subtractProductAndSum(n);
        System.out.println(sub);
    }

    public static int subtractProductAndSum(int n) {
        int sum = 0;
        int prod = 1;
        while (n != 0) {
            int mod = n % 10;
            sum += mod;
            prod *= mod;
            n /= 10;
        }
        return prod - sum;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int subtractProductAndSum(int n
{
        int sum = 0;
        int prod = 1;
        while (n != 0) {
            int mod = n % 10;
            sum += mod;
            prod *= mod;
            n /= 10;
        }
        return prod - sum;
}

int main()
{
    int n = 245;
    int sub = subtractProductAndSum(n);
    cout<<sub<<"\n";
    return 0;
}


No comments:

Post a Comment