leetcode菜雞鬥智鬥勇系列(4)--- 單一數字的乘積和總合的減法

1.原題:

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方法

 

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); }};

相關文章
相關標籤/搜索