|
| 1 | +// Source : https://leetcode.com/problems/maximum-value-after-insertion/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-05-30 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given a very large integer n, represented as a string, and an integer digit x. The |
| 8 | + * digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative |
| 9 | + * number. |
| 10 | + * |
| 11 | + * You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n |
| 12 | + * . You cannot insert x to the left of the negative sign. |
| 13 | + * |
| 14 | + * For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763. |
| 15 | + * If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255. |
| 16 | + * |
| 17 | + * Return a string representing the maximum value of n after the insertion. |
| 18 | + * |
| 19 | + * Example 1: |
| 20 | + * |
| 21 | + * Input: n = "99", x = 9 |
| 22 | + * Output: "999" |
| 23 | + * Explanation: The result is the same regardless of where you insert 9. |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * |
| 27 | + * Input: n = "-13", x = 2 |
| 28 | + * Output: "-123" |
| 29 | + * Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123. |
| 30 | + * |
| 31 | + * Constraints: |
| 32 | + * |
| 33 | + * 1 <= n.length <= 10^5 |
| 34 | + * 1 <= x <= 9 |
| 35 | + * The digits in n are in the range [1, 9]. |
| 36 | + * n is a valid representation of an integer. |
| 37 | + * In the case of a negative n, it will begin with '-'. |
| 38 | + ******************************************************************************************************/ |
| 39 | + |
| 40 | +class Solution { |
| 41 | +public: |
| 42 | + string maxValue(string n, int x) { |
| 43 | + bool neg = false; |
| 44 | + if (n[0] == '-') neg = true; |
| 45 | + |
| 46 | + int i; |
| 47 | + |
| 48 | + for( i=neg?1:0; i<n.size(); i++){ |
| 49 | + if (neg == true) { |
| 50 | + if ( n[i]-'0' > x) break; |
| 51 | + }else{ |
| 52 | + if (n[i]-'0' < x) break; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + n.insert(n.begin()+i, x+'0'); |
| 57 | + return n; |
| 58 | + } |
| 59 | +}; |
0 commit comments