[LeetCode] Difference Between Element Sum and Digit Sum of an Array

2535. Difference Between Element Sum and Digit Sum of an Array

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|.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int differenceOfSum(vector<int>& nums) {
long long s1 = 0, s2 = 0;
for(auto n : nums) {
s1 += n;
while(n) {
s2 += n % 10;
n /= 10;
}
}
return abs(s1-s2);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/15/PS/LeetCode/difference-between-maximum-and-minimum-price-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.