Difference Between Element Sum and Digit Sum of an Array
Problem
The element sum is the sum of all elements in nums. The digit sum is the sum of all the digits (treating each number digit by digit). Return the absolute difference between the element sum and the digit sum.
nums = [1,15,6,3]9def difference_of_sum(nums):
element_sum = sum(nums)
digit_sum = 0
for x in nums:
while x > 0:
digit_sum += x % 10
x //= 10
return abs(element_sum - digit_sum)
function differenceOfSum(nums) {
let elementSum = 0, digitSum = 0;
for (let x of nums) {
elementSum += x;
while (x > 0) { digitSum += x % 10; x = Math.floor(x / 10); }
}
return Math.abs(elementSum - digitSum);
}
class Solution {
public int differenceOfSum(int[] nums) {
int elementSum = 0, digitSum = 0;
for (int x : nums) {
elementSum += x;
while (x > 0) { digitSum += x % 10; x /= 10; }
}
return Math.abs(elementSum - digitSum);
}
}
int differenceOfSum(vector<int>& nums) {
int elementSum = 0, digitSum = 0;
for (int x : nums) {
elementSum += x;
while (x > 0) { digitSum += x % 10; x /= 10; }
}
return abs(elementSum - digitSum);
}
Explanation
We need two independent totals. The element sum is just every number added together. The digit sum breaks each number into its digits and adds those instead, so 15 contributes 1 + 5 = 6.
To peel digits off a number we repeatedly take x % 10 (the last digit) and then integer-divide x // 10 to chop it off, until x reaches zero.
We can compute both sums in a single pass: for each value add it to elementSum, then loop to extract its digits into digitSum.
Finally we return the absolute difference. Since each element is at least as large as its digit sum, the element sum is never smaller, but the absolute value keeps the answer non-negative regardless.
Example: [1,15,6,3]. Element sum = 1+15+6+3 = 25. Digit sum = 1 + (1+5) + 6 + 3 = 16. Answer = |25 − 16| = 9.