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
思路:取最后一位 % 10;
class Solution {
public int subtractProductAndSum(int n) {
return (product(n) - sum(n));
}
private int product(int n) {
int res = 1;
while(n != 0) {
int num = n % 10;
n = n / 10;
res *= num;
}
return res;
}
private int sum(int n) {
int res = 0;
while(n != 0) {
int num = n % 10;
n = n / 10;
res += num;
}
return res;
}
}