leetcode菜鸡斗智斗勇系列(4)--- 单一数字的乘积和总合的减法

1.原题:

https://leetcode.com/problems/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.

翻译:给定一个数字n,返回乘积和总合的差。

理论上的输入输出:

Input: n = 234

Output: 15

Explanation:

Product of digits = 2 * 3 * 4 = 24

Sum of digits = 2 + 3 + 4 = 9

Result = 24 - 9 = 15

2.解题思路:

应该来说是最简单的问题了,这里我们用的是 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);
}
};




猜你喜欢

转载自www.cnblogs.com/cptCarlvon/p/12055010.html
今日推荐