Given an integer number
Example:
n = 234
output = 15 which is ((2*3*4) - (2+3+4))
Solution in C++:
int subtractProductAndSum(int n) {
int sum = 0;
int prd = 0;
int tmp = 0;
bool is_first = true;
while(n != 0){
tmp = n % 10;
n = n / 10;
sum += tmp;
if(is_first){
is_first = false;
prd = tmp;
} else {
prd *= tmp;
}
}
return prd - sum;
}
n, return the difference between the product of its digits and the sum of its digits.Example:
n = 234
output = 15 which is ((2*3*4) - (2+3+4))
Solution in C++:
int subtractProductAndSum(int n) {
int sum = 0;
int prd = 0;
int tmp = 0;
bool is_first = true;
while(n != 0){
tmp = n % 10;
n = n / 10;
sum += tmp;
if(is_first){
is_first = false;
prd = tmp;
} else {
prd *= tmp;
}
}
return prd - sum;
}
Comments
Post a Comment