原文链接: https://leetcode-cn.com/problems/maximum-value-after-insertion
英文原文
You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.
You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign.
- For example, if
n = 73andx = 6, it would be best to insert it between7and3, makingn = 763. - If
n = -55andx = 2, it would be best to insert it before the first5, makingn = -255.
Return a string representing the maximum value of n after the insertion.
Example 1:
Input: n = "99", x = 9 Output: "999" Explanation: The result is the same regardless of where you insert 9.
Example 2:
Input: n = "-13", x = 2
Output: "-123"
Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.
Constraints:
1 <= n.length <= 1051 <= x <= 9- The digits in
n are in the range[1, 9]. nis a valid representation of an integer.- In the case of a negative
n, it will begin with'-'.
中文题目
给你一个非常大的整数 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表示负数时,将会以字符'-'开始。
通过代码
高赞题解
- 对于正数,插入位置左侧的数字都必须 $\ge x$
- 对于负数,插入位置左侧的数字都必须 $\le x$
func maxValue(n string, x int) string {
y := byte('0' + x)
i := 0
if n[0] != '-' {
for ; i < len(n) && n[i] >= y; i++ {}
} else {
for i = 1; i < len(n) && n[i] <= y; i++ {}
}
return n[:i] + string(y) + n[i:]
}
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 6309 | 17762 | 35.5% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|