Maximum Value after Insertion LeetCode solution in C++

1
class Solution {
2
public:
3
string maxValue(string s, int x) {
4
int p = 0, flag = 0;
5
char ch = '0' + x; // change int to char
6
string str;
7

8
if (s[0] == '-') { // for negative numbers
9
for (int i = 1; i < s.size(); i++) {
10
if (ch < s[i] && !flag) {
11
str += ch;
12
str += s[i];
13
flag = 1;
14
} else
15
str += s[i];
16
}
17
if (!flag) str += ch;
18
return '-' + str;
19
}
20

21
// if number is positive
22
for (int i = 0; i < s.size(); i++) {
23
if (ch > s[i] && !flag) {
24
str += ch;
25
str += s[i];
26
flag = 1;
27
} else
28
str += s[i];
29
}
30
if (!flag) str += ch;
31
return str;
32
}
33
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0