小U的数字插入问题

64 阅读2分钟

问题描述

小U手中有两个数字 a 和 b。第一个数字是一个任意的正整数,而第二个数字是一个非负整数。她的任务是将第二个数字 b 插入到第一个数字 a 的某个位置,以形成一个最大的可能数字。

你需要帮助小U找到这个插入位置,输出插入后的最大结果。

解题思路

  1. 遍历字符串 a

    • 使用 for 循环从 0 到 a.length() - 1 遍历字符串 a 的每个字符。
  2. 比较字符

    • 在每次循环中,使用 b.compareTo(a.substring(i, i + 1)) 比较 b 和 a 中从位置 i 开始的子字符串。

    • compareTo 方法返回一个整数,表示两个字符串的字典序关系:

      • 如果 b 大于 a.substring(i, i + 1),返回值大于 0
      • 如果 b 小于 a.substring(i, i + 1),返回值小于 0
      • 如果 b 等于 a.substring(i, i + 1),返回值等于 0
  3. 插入字符串 b

    • 如果 b 大于 a.substring(i, i + 1),则将 b 插入到位置 i,返回 a.substring(0, i) + b + a.substring(i)
  4. 处理未找到合适位置的情况

    • 如果遍历完字符串 a 仍未找到合适的插入位置,则将 b 插入到字符串 a 的末尾,返回 a + b

代码解析

public class Main {
    public static int solution(int a, int b) {
        String strA = Integer.toString(a);
        String strB = Integer.toString(b);

        // 遍历字符串 a,找到合适的插入位置
        for (int i = 0; i < strA.length(); i++) {
            if (strB.charAt(0) > strA.charAt(i)) {
                // 如果 b 的第一个字符大于当前字符的值,则将 b 插入到当前位置
                return Integer.parseInt(strA.substring(0, i) + strB + strA.substring(i));
            }
            if (strA.charAt(i) == strB.charAt(0)) {
                int j = 1;
                while (j < strB.length() && i + j < strA.length()) {
                    if (strB.charAt(j) > strA.charAt(i + j)) {
                        // 如果 b 的后续字符大于 a 的后续字符,则将 b 插入到当前位置
                        return Integer.parseInt(strA.substring(0, i) + strB + strA.substring(i));
                    } else if (strB.charAt(j) < strA.charAt(i + j)) {
                        // 如果 b 的后续字符小于 a 的后续字符,则继续遍历
                        break;
                    }
                    j++;
                }
            }
        }

        // 如果没有找到合适的插入位置,则将 b 插入到最后
        return Integer.parseInt(strA + strB);
    }

    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);
    }
}