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:
c 复制代码
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;
}
相关推荐
forest_0910 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
纪念 22911 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
文丑颜不良啊14 小时前
LeetCode2761~2780题目解析
java·leetcode
jyOverQ14 小时前
从零学 JVM(六):垃圾回收算法详解——标记清除、标记复制与标记整理
jvm·算法
严肃小白兔16 小时前
第 06/24 期:神经网络的反向传播算法:从链式法则到梯度计算
人工智能·神经网络·算法
落羽的落羽17 小时前
【C++】C++17的主要特性
linux·服务器·开发语言·c++·算法·机器学习
文丑颜不良啊17 小时前
LeetCode2841~2860题目解析
java·leetcode
【心态好不摆烂】17 小时前
数据结构基础精讲3
数据结构·算法
漂流瓶jz18 小时前
UVA-1613 K度图的着色 题解答案代码 算法竞赛入门经典第二版
算法·深度优先·图论·贪心·aoapc·算法竞赛入门经典·uva