#2535
Easy Algorithms Difference between element sum and digit sum of an array
Array Math
85.3% acceptance
Feb 25, 2026
811
30
You are given a positive integer array nums.
The element sum is the sum of all the elements in nums.
The digit sum is the sum of all the digits (not necessarily distinct) that appear in nums.
Return the absolute difference between the element sum and digit sum of nums.
Note that the absolute difference between two integers x and y is defined as |x - y|.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn difference_of_sum(nums: Vec<i32>) -> i32 {
let elem_sum: i32 = nums.iter().sum();
let digit_sum: i32 = nums
.iter()
.map(|&x| {
let mut s = 0;
let mut n = x;
while n > 0 {
s += n % 10;
n /= 10;
}
s
})
.sum();
(elem_sum - digit_sum).abs()
}
}