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

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

思路1 正常写就好 #

分析 #

  • 数字和肯定大于等于位和,不用写绝对值

代码 #

 1func differenceOfSum(nums []int) int {
 2	l, r := 0, 0
 3	for _, v := range nums {
 4		l += v
 5		for _, v1 := range fmt.Sprint(v) {
 6			r += int(v1 - '0')
 7		}
 8	}
 9	return l - r
10}