| comments | true | ||
|---|---|---|---|
| difficulty | 中等 | ||
| edit_url | https://github.com/doocs/leetcode/edit/main/solution/1800-1899/1881.Maximum%20Value%20after%20Insertion/README.md | ||
| rating | 1381 | ||
| source | 第 243 场周赛 Q2 | ||
| tags |
|
给你一个非常大的整数 n 和一个整数数字 x ,大整数 n 用一个字符串表示。n 中每一位数字和数字 x 都处于闭区间 [1, 9] 中,且 n 可能表示一个 负数 。
你打算通过在 n 的十进制表示的任意位置插入 x 来 最大化 n 的 数值 。但 不能 在负号的左边插入 x 。
- 例如,如果
n = 73且x = 6,那么最佳方案是将6插入7和3之间,使n = 763。 - 如果
n = -55且x = 2,那么最佳方案是将2插在第一个5之前,使n = -255。
返回插入操作后,用字符串表示的 n 的最大值。
示例 1:
输入:n = "99", x = 9 输出:"999" 解释:不管在哪里插入 9 ,结果都是相同的。
示例 2:
输入:n = "-13", x = 2 输出:"-123" 解释:向 n 中插入 x 可以得到 -213、-123 或者 -132 ,三者中最大的是 -123 。
提示:
1 <= n.length <= 1051 <= x <= 9n 中每一位的数字都在闭区间[1, 9]中。n代表一个有效的整数。- 当
n表示负数时,将会以字符'-'开始。
如果
时间复杂度
class Solution:
def maxValue(self, n: str, x: int) -> str:
i = 0
if n[0] == "-":
i += 1
while i < len(n) and int(n[i]) <= x:
i += 1
else:
while i < len(n) and int(n[i]) >= x:
i += 1
return n[:i] + str(x) + n[i:]class Solution {
public String maxValue(String n, int x) {
int i = 0;
if (n.charAt(0) == '-') {
++i;
while (i < n.length() && n.charAt(i) - '0' <= x) {
++i;
}
} else {
while (i < n.length() && n.charAt(i) - '0' >= x) {
++i;
}
}
return n.substring(0, i) + x + n.substring(i);
}
}class Solution {
public:
string maxValue(string n, int x) {
int i = 0;
if (n[0] == '-') {
++i;
while (i < n.size() && n[i] - '0' <= x) {
++i;
}
} else {
while (i < n.size() && n[i] - '0' >= x) {
++i;
}
}
n.insert(i, 1, x + '0');
return n;
}
};func maxValue(n string, x int) string {
i := 0
y := byte('0' + x)
if n[0] == '-' {
i++
for i < len(n) && n[i] <= y {
i++
}
} else {
for i < len(n) && n[i] >= y {
i++
}
}
return n[:i] + string(y) + n[i:]
}function maxValue(n: string, x: number): string {
let i = 0;
if (n[0] === '-') {
i++;
while (i < n.length && +n[i] <= x) {
i++;
}
} else {
while (i < n.length && +n[i] >= x) {
i++;
}
}
return n.slice(0, i) + x + n.slice(i);
}impl Solution {
pub fn max_value(n: String, x: i32) -> String {
let s = n.as_bytes();
let mut i = 0;
if n.starts_with('-') {
i += 1;
while i < s.len() && (s[i] - b'0') as i32 <= x {
i += 1;
}
} else {
while i < s.len() && (s[i] - b'0') as i32 >= x {
i += 1;
}
}
let mut ans = String::new();
ans.push_str(&n[0..i]);
ans.push_str(&x.to_string());
ans.push_str(&n[i..]);
ans
}
}/**
* @param {string} n
* @param {number} x
* @return {string}
*/
var maxValue = function (n, x) {
let i = 0;
if (n[0] === '-') {
i++;
while (i < n.length && +n[i] <= x) {
i++;
}
} else {
while (i < n.length && +n[i] >= x) {
i++;
}
}
return n.slice(0, i) + x + n.slice(i);
};