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);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/45224.html
標籤:其他
下一篇:解決問題的能力 > 10倍程式員
