Difference Between Element Sum and Digit Sum of an Array

Tags : leetcode, array, math, cpp, easy

You are given a positive integer array 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|.

Examples #

Example 1:

Input: nums = [1,15,6,3]
Output: 9
Explanation: 
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.

Example 2:

Input: nums = [1,2,3,4]
Output: 0
Explanation:
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.

Constraints #

Solutions #


class Solution {
public:
    int differenceOfSum(vector<int>& nums) {
        int dig_sum = 0, tot_sum = 0;
        for(int i: nums) {
            tot_sum += i;
            while(i) {
                dig_sum += i % 10;
                i /= 10;
            }
        }
        return abs(tot_sum - dig_sum);
    }
};