字节面试题,数组A中给定可以使用的1~9的数,返回由A数组中的元素组成的小于n的最大数。例如A={1, 2, 4, 9},x=2533,返回2499

import java.util.*;

public class Main {

    public static void main(String[] args) {
        int[] A = {1,2,4,9};
        int x = 2533;
        int i = new Main().maxNum(A,x);
        System.out.println(i);
    }

    private int max = 0;
    private TreeSet<Integer> set = new TreeSet<>();
    //传入 数组A 和 x
    public int maxNum(int[] A, int x){
        for (int i : A) {
            set.add(i);
            max = Math.max(max,i);
        }
        return dfs(x-1);
    }

    int dfs(int x){
        if (x<=0) return 0;
        int res = 0, is = -1;
        char[] chars = (x + "").toCharArray();
        for (char c : chars) {
            if (is!=-1){
                res = res*10 + max;
                continue;
            }
            if(set.contains(c-'0')){
                res = res*10+(c-'0');
                continue;
            }
            if(set.lower(c-'0')!=null) res = res*10+set.lower(c-'0');
            else res = dfs(res-1)*10+max;
            is = 1;
        }
        return res;
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值