[코테 풀이] Difference Between Element Sum and Digit Sum of an Array

시내·2024년 6월 14일

Q_2535) Difference Between Element Sum and Digit Sum of an Array

출처 : https://leetcode.com/problems/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|.

class Solution {
    public int differenceOfSum(int[] nums) {
        int a = 0;
        int b = 0;
        for(int n : nums){
            a += n;
        }
        for(int m = 0; m < nums.length; m++){
            String str = Integer.toString(nums[m]);
            for(int q = 0; q < str.length(); q++){
                b+=str.charAt(q)-'0';
            }
        }
        return Math.abs(a-b);
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글