728x90
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.
나의 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/**
* @param {number[]} nums
* @return {number}
*/
var differenceOfSum = function(nums) {
const answer = []
let hap1 = 0
let hap2 = 0
nums.forEach((num)=>{
hap1+=num
})
answer.push(hap1)
nums.join('').split('').forEach((num)=>[
hap2+=Number(num)
])
answer.push(hap2)
return answer[0] - answer[1]
};
|
cs |
728x90
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
[프로그래머스] 최대공약수와 최소공배수 (0) | 2023.01.21 |
---|---|
[Leet Code - eazy] 1480. Running Sum of 1d Array (0) | 2023.01.21 |
[Leet Code - eazy] 2011. Final Value of Variable After Performing Operations (0) | 2023.01.21 |
[Leet Code - eazy] 1108. Defanging an IP Address (0) | 2023.01.21 |
[프로그래머스] 부족한 금액 계산하기 (0) | 2023.01.20 |