小U的数字插入问题 | 豆包MarsCode AI刷题

22 阅读1分钟
public class Main {
    public static int solution(int a, int b) {
        // 将数字 a 和 b 转换为字符串
        String strA = Integer.toString(a);
        String strB = Integer.toString(b);
        
        // 初始化最大结果
        String maxResult = strA;
        
        // 遍历字符串 a 的每个位置
        for (int i = 0; i <= strA.length(); i++) {
            // 尝试将 b 插入到位置 i
            String newResult = strA.substring(0, i) + strB + strA.substring(i);
            
            // 比较新结果和当前最大结果
            if (newResult.compareTo(maxResult) > 0) {
                maxResult = newResult;
            }
        }
        
        // 将最大结果转换回整数并返回
        return Integer.parseInt(maxResult);
    }

    public static void main(String[] args) {
        System.out.println(solution(76543, 4) == 765443);
        System.out.println(solution(1, 0) == 10);
        System.out.println(solution(44, 5) == 544);
        System.out.println(solution(666, 6) == 6666);
    }
}