https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/git
Given an integer number n
, return the difference between the product of its digits and the sum of its digits.spa
翻译:给定一个数字n,返回乘积和总合的差。翻译
理论上的输入输出:code
Input: n = 234 leetcode
Output: 15 get
Explanation: it
Product of digits = 2 * 3 * 4 = 24io
Sum of digits = 2 + 3 + 4 = 9class
Result = 24 - 9 = 15方法
应该来讲是最简单的问题了,这里咱们用的是 n % 10的方法,%得出的结果是两个数相除后的余数,所以你对任何正整数用,结果都是其最小位的数字。
而后获得小数以后,使用 / 除法操做符,由于是int,因此不用担忧小数。
class Solution {public: int subtractProductAndSum(int n) { int pd = 1; int sd = 0; for (;n > 0 ; n /= 10) { pd *= n%10; sd += n%10; } return (pd-sd); }};