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;
}
相关推荐
拓恒技术2 小时前
无人机巡检AI算法的工程化落地:从需求到交付的5个核心环节
人工智能·算法·无人机
晨曦中的暮雨2 小时前
限流算法——固定窗口、滑动窗口、漏桶、令牌桶
java·开发语言·算法
怕浪猫2 小时前
Claude Code vs Codex:Computer Use 实现原理深度拆解
算法·面试·github
文丑颜不良啊4 小时前
LeetCode876~900题目解析
java·leetcode
罗西的思考4 小时前
AI 时代的 “房谋杜断”:如何培养能力、品味与判断力
人工智能·算法·机器学习
淡海水4 小时前
07-02-源码-.NET Core GC分配路径
算法·unity·c#·.netcore·gc·1024程序员节
下一站春风里6 小时前
位运算完整学习笔记:按位与(&)+ 异或(^)
开发语言·c++·算法
DRobot6 小时前
【机械制图与CAD实战(二十五)】螺纹的表示方法
算法·机械制图
用户老李7 小时前
卡尔曼滤波自学教程 10:无迹卡尔曼滤波(UKF)
算法
深圳市益普科技有限公司8 小时前
半导体良率管理YMS:良率与设备参数的相关性,先拉哪几组数据
人工智能·python·算法