LeetCode最大数字范围的整数之和

LeetCode第509场周赛Q1最大数字范围的整数之和

date:2026-07-05

题目

给你一个整数数组 nums。

一个整数的 数字范围 定义为其 最大 数字与 最小 数字之间的差。

例如,5724 的数字范围为 7 - 2 = 5。

返回 nums 中所有 数字范围 等于数组中 最大数字范围 的整数之和。

示例 1:

输入: nums = 5724,111,350

输出: 6074

解释:

最大数字范围为 5。数字范围为 5 的整数是 5724 和 350,因此答案为 5724 + 350 = 6074。

示例 2:

输入: nums = 90,900

输出: 990

解释:

最大数字范围为 9。两个整数的数字范围都是 9 ,因此答案为 90 + 900 = 990。

提示:

1 <= nums.length <= 100

10 <= numsi <= 105©leetcode

题解

利用char比较

直接遍历数组,找到最大数字范围的整数,并把它们加到结果中。

求数字范围:数字转化成string,然后找到里面的最大char和最小char,得到数字范围。

java 复制代码
class Solution {
    public int maxDigitRange(int[] nums) {
        int res = 0;
        int maxR = 0;
        for (int v : nums) {
            int range = getRange(v);
            if (range > maxR) {
                maxR = range;
                res = v;
            } else if (range == maxR) {
                res += v;
            }
        }

        return res;
    }

    private int getRange(int v) {
        String s = "" + v;
        char max = '0';
        char min = '9';
        for (char ch : s.toCharArray()) {
            if (ch > max) {
                max = ch;
            }

            if (ch < min) {
                min = ch;
            }
        }

        return max - min;
    }
}©leetcode

直接用除法找数字

java 复制代码
   private int getRange(int v) {
        int max = 0;
        int min = 9;
        while (v != 0) {
            int d = v % 10;
            v /= 10;
            if (max < d) {
                max = d;
            }
            if (min > d) {
                min = d;
            }
        }

        return max - min;
    }©leetcode