Skip to main content
Back to problems
#1281
Easy Algorithms

Subtract the product and sum of digits of an integer

Math
86.6% acceptance
Feb 25, 2026
2824
253
Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn subtract_product_and_sum(n: i32) -> i32 {
    let mut n = n;
    let mut product = 1;
    let mut sum = 0;
    while n > 0 {
      let d = n % 10;
      product *= d;
      sum += d;
      n /= 10;
    }
    product - sum
  }
}