carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2535: Difference Between Element Sum and Digit Sum of an Array #414

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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

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:

1 <= nums.length <= 2000 1 <= nums[i] <= 2000

carloscn commented 1 year ago

Analysis

static int32_t difference_of_sum(int32_t* nums, size_t nums_size)
{
    int32_t ret = 0;

    UTILS_CHECK_PTR(nums);
    UTILS_CHECK_LEN(nums_size);

    for (size_t i = 0; i < nums_size; i ++) {
        int32_t t = 0, e = nums[i];
        while (e != 0) {
            t += e % 10;
            e /= 10;
        }
        ret += nums[i] - t;
    }

finish:
    return utils_int32_abs(ret);
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1171784 https://github.com/carloscn/structstudy/commit/0927dca07362d32e72ee69198cc483e8ed719df4