首页 > 基础资料 博客日记

2026-07-05最大数字范围的整数之和

2026-07-05 19:30:02基础资料围观16

文章2026-07-05最大数字范围的整数之和分享给大家,欢迎收藏极客资料网,专注分享技术知识

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 <= nums[i] <= 105©leetcode

题解

利用char比较

直接遍历数组,找到最大数字范围的整数,并把它们加到结果中。
求数字范围:数字转化成string,然后找到里面的最大char和最小char,得到数字范围。

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

直接用除法找数字

   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

文章来源:https://www.cnblogs.com/FannyChung/p/21145049/20260705zui-da-shu-zi-fan-wei-de-zheng-shu-zhi-he
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云