Skip to content

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

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int differenceOfSum(vector<int>& nums) {
    const int elementSum = accumulate(nums.begin(), nums.end(), 0);
    const int allDigitSum = getAllDigitSum(nums);
    return abs(elementSum - allDigitSum);
  }

 private:
  int getAllDigitSum(const vector<int>& nums) {
    int allDigitSum = 0;
    for (const int num : nums)
      allDigitSum += getDigitSum(num);
    return allDigitSum;
  }

  int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int differenceOfSum(int[] nums) {
    final int elementSum = Arrays.stream(nums).sum();
    final int allDigitSum = getAllDigitSum(nums);
    return Math.abs(elementSum - allDigitSum);
  }

  private int getAllDigitSum(int[] nums) {
    int allDigitSum = 0;
    for (final int num : nums)
      allDigitSum += getDigitSum(num);
    return allDigitSum;
  }

  private int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def differenceOfSum(self, nums: list[int]) -> int:
    elementSum = sum(nums)
    digitSum = self._getAllDigitSum(nums)
    return abs(elementSum - digitSum)

  def _getAllDigitSum(self, nums: list[int]) -> int:
    return sum(self._getDigitSum(num) for num in nums)

  def _getDigitSum(self, num: int) -> int:
    return sum(int(digit) for digit in str(num))