Navigator_Z头像
关注
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer封面图

LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer

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

From: LeetCode
Link: 1281. Subtract the Product and Sum of Digits of an Integer


Solution:

Ideas:

Extract each digit using % 10, update the product and sum, then return res - sum.

Code:
int subtractProductAndSum(int n) {
    int num = n;
    int sum = 0;
    int res = 1;
    while(num != 0){
        sum += num % 10;
        res *= num % 10;
        num /= 10;
    }
    return res - sum;
}

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/navicheung/article/details/162805752

文章来源转载

评论

赞0

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--