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

题目

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)//遍历

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值