1.문제
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|.
정수 배열이 주어질 때 배열의 숫자들의 합과 숫자들의 digit 단위 합의 절댓값 차를 구하면 되는 문제이다.
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
2.풀이
- nums를 순회하면서 elementSum 을 구한다.
- nums의 숫자들을 digit 단위로 쪼개어서 배열에 저장한다.
- digit 배열을 순회하면서 digitSum을 구한다.
- 두 합의 차의 절댓값을 리턴한다.
/**
* @param {number[]} nums
* @return {number}
*/
const differenceOfSum = function (nums) {
let elementSum = 0;
let digitSum = 0;
const digitArray = [];
// elementSum 구하기
for (let i = 0; i < nums.length; i++) {
elementSum += nums[i];
}
// nums 배열의 숫자들을 digit 단위로 쪼개어서 배열에 저장한다.
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < String(nums[i]).length; j++) {
digitArray.push(String(nums[i])[j]);
}
}
// digit들의 합을 구한다.
for (let i = 0; i < digitArray.length; i++) {
digitSum += parseInt(digitArray[i]);
}
// elementSum - digitSum 의 절댓값을 리턴
return Math.abs(elementSum - digitSum);
};
3.결과
