You are given a very large integer n, represented as a string,negative 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 negative. You cannot insert x to the left of the negative sign.
For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.
If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.
Return a string representing the maximum value of negative after the insertion.
題目給一個非常大的整數n(字串形式表示),還有一個整數x。n和x的每個數字都在1~9的範圍,但n可能是負數!目標是通過將數字x插入到n的十進位表示中來使得n的數值最大化(但不能把x插入到負號左邊)
返回插入後n數值最大化的字串
我的解題思路:
class Solution {
public String maxValue(String n, int x) {
if (n.charAt(0) == '-') {
for (int i = 1; i < n.length(); i++) {
// 如果x小於目前數字,就把x插入
if (x < n.charAt(i) - '0') {
return n.substring(0, i) + x + n.substring(i);
}
}
// x是最大的數字就直接放尾巴
return n + x;
}else {
for (int i = 0; i < n.length(); i++) {
// 如果x大於目前數字,就把x插入
if (x > n.charAt(i) - '0') {
return n.substring(0, i) + x + n.substring(i);
}
}
// x是最小的數字就直接放尾巴
return n + x;
}
}
}
輕輕鬆鬆!