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;
}
相关推荐
Tisfy36 分钟前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战61740 分钟前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
羊在吃青草1 小时前
C语言之数组
c语言·数据结构
灯澜忆梦1 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
烟烟Abandon1 小时前
FFmpeg开发基础之 C 语言中的文件操作
c语言·ffmpeg
Shaoshing2 小时前
LeetCode100 155.最小栈
java·数据结构·算法
秋天的怀念_David3 小时前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法
纪念 2293 小时前
C++ 算法模板与错题 (差分)
开发语言·c++·算法
echoliuy3 小时前
二叉树—二叉搜索树 前序 中序 后序
算法·深度优先