leetcode.每日一题.2535.数组元素和与数字和的绝对差

发布于:2024-10-12 ⋅ 阅读:(123) ⋅ 点赞:(0)

题目

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

第一遍AC代码

利用了to_string(),将数字转化成字符串。

class Solution {
public:
    int differenceOfSum(vector<int>& nums) {
        long long x=0,y=0;
        for(int i=0;i<nums.size();i++)
        {
            x+=nums[i];
            string s=to_string(nums[i]);
            for(int j=0;j<s.length();j++)
            {
                y+=int(s[j]-'0');
            }
        }
        // cout<<x<<endl;
        // cout<<y<<endl;
        int res=abs(x-y);
        return res;

        
    }
};

官方题解,使用while循环提取每一位

class Solution {
public:
    int differenceOfSum(vector<int>& nums) {
        int elementSum = 0, digitSum = 0;
        for (int num : nums) {
            elementSum += num;
            while (num > 0) {
                digitSum += num % 10;
                num /= 10;
            }
        }
        return elementSum - digitSum;
    }
};

作者:力扣官方题解
链接:https://leetcode.cn/problems/difference-between-element-sum-and-digit-sum-of-an-array/solutions/2930819/shu-zu-yuan-su-he-yu-shu-zi-he-de-jue-du-0oy2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 很简单,没什么要说的

补充

for(int i:vec)//遍历

 


网站公告

今日签到

点亮在社区的每一天
去签到