建设移动网站,淮北论坛招聘网,在线商城网站怎么做,wordpress 数据库 开发【LetMeFly】2535.数组元素和与数字和的绝对差#xff1a;模拟
力扣题目链接#xff1a;https://leetcode.cn/problems/difference-between-element-sum-and-digit-sum-of-an-array/
给你一个正整数数组 nums 。
元素和 是 nums 中的所有元素相加求和。数字和 是 nums 中每…【LetMeFly】2535.数组元素和与数字和的绝对差模拟
力扣题目链接https://leetcode.cn/problems/difference-between-element-sum-and-digit-sum-of-an-array/
给你一个正整数数组 nums 。
元素和 是 nums 中的所有元素相加求和。数字和 是 nums 中每一个元素的每一数位重复数位需多次求和相加求和。
返回 元素和 与 数字和 的绝对差。
注意两个整数 x 和 y 的绝对差定义为 |x - y| 。 示例 1
输入nums [1,15,6,3]
输出9
解释
nums 的元素和是 1 15 6 3 25 。
nums 的数字和是 1 1 5 6 3 16 。
元素和与数字和的绝对差是 |25 - 16| 9 。示例 2
输入nums [1,2,3,4]
输出0
解释
nums 的元素和是 1 2 3 4 10 。
nums 的数字和是 1 2 3 4 10 。
元素和与数字和的绝对差是 |10 - 10| 0 。提示
1 nums.length 20001 nums[i] 2000
解题方法模拟
写一个函数getSum(x)返回整数x在十进制下的每位之和
int getSum(int x) {int ans 0;while (x 0) {ans x % 10;x / 10;}return ans;
}使用两个变量x和y分别记录元素之和和元素每一位之和遍历一遍原始数组即可得到这个值。
最终返回abs(x - y)即为答案。
时间复杂度 O ( l e n ( n u m s ) × log M ) O(len(nums)\times \log M) O(len(nums)×logM)其中 M M M是 n u m s [ i ] nums[i] nums[i]可取值范围的最大值 2000 2000 2000。空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C
class Solution {
private:int getSum(int n) {int ans 0;while (n) {ans n % 10;n / 10;}return ans;}
public:int differenceOfSum(vectorint nums) {int x 0, y 0;for (int t : nums) {x t, y getSum(t);}return abs(x - y);}
};Go
package mainfunc abs(x int) int {if x 0 {return x}return -x
}func getSum(x int) int {ans : 0for x 0 {ans x % 10x / 10}return ans
}func differenceOfSum(nums []int) int {x, y : 0, 0for _, t : range nums {x ty getSum(t)}return abs(x - y)
}Java
class Solution {private int getSum(int t) {int ans 0;while (t 0) {ans t % 10;t / 10;}return ans;}public int differenceOfSum(int[] nums) {int x 0, y 0;for (int t : nums) {x t;y getSum(t);}return Math.abs(x - y);}
}Python
from typing import Listclass Solution:def getSum(self, x: int) - int:ans 0while x:ans x % 10x // 10return ansdef differenceOfSum(self, nums: List[int]) - int:x y 0for t in nums:x ty self.getSum(t)return abs(x - y)同步发文于CSDN和我的个人博客原创不易转载经作者同意后请附上原文链接哦~ Tisfyhttps://letmefly.blog.csdn.net/article/details/142568318