---
tags: LeetCode
---
# 1281. 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.
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
Example 2:
- Input: n = 4421
- Output: 21
- Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
Constraints:
- 1 <= n <= 10^5
輸入範本如下
```C#
public class Solution {
public int SubtractProductAndSum(int n)
{
}
}
```
---
### 直覺想法
怎麼取出一個數字的每個位數是多少 以及 輸入一定大於等於 1
, 這代表輸入不可能是負數
1. % 10 運算可以得到個位數 , 在除以 10後 , 再做一次 % 10 運算
```
public int SubtractProductAndSum(int n)
{
int product = 1;
int sum = 0;
while (n > 0)
{
int digit = n % 10;
product *= digit;
sum += digit;
n /= 10;
}
return product - sum;
}
```
2. 先轉成 string 再轉回 int --- Convert 方法
```C#
public int SubtractProductAndSum(int n)
{
string number = n.ToString();
// number[0].ToString() 需要 ToString() , 否則會變成 ASCII 碼
int product = Convert.ToInt32(number[0].ToString());
int sum = Convert.ToInt32(number[0].ToString());
for (int i = 1; i < number.Length; i++)
{
sum += Convert.ToInt32((number[i].ToString()));
product *= Convert.ToInt32((number[i].ToString()));
}
return product - sum;
}
```
### Thank you!
You can find me on
- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)
若有謬誤 , 煩請告知 , 新手發帖請多包涵
# :100: :muscle: :tada: :sheep: