问题描述
小U手中有两个数字 a 和 b。第一个数字是一个任意的正整数,而第二个数字是一个非负整数。她的任务是将第二个数字 b 插入到第一个数字 a 的某个位置,以形成一个最大的可能数字。
你需要帮助小U找到这个插入位置,输出插入后的最大结果。
解题思路
-
遍历字符串
a:- 使用
for循环从0到a.length() - 1遍历字符串a的每个字符。
- 使用
-
比较字符:
-
在每次循环中,使用
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。
- 如果
-
-
插入字符串
b:- 如果
b大于a.substring(i, i + 1),则将b插入到位置i,返回a.substring(0, i) + b + a.substring(i)。
- 如果
-
处理未找到合适位置的情况:
- 如果遍历完字符串
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);
}
}