Skip to content

Commit 85042b4

Browse files
Create Day 13 Remove K Digits.cpp
1 parent 02d35fd commit 85042b4

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Day 13 Remove K Digits.cpp

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
PROBLEM:
2+
3+
4+
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
5+
6+
Note:
7+
The length of num is less than 10002 and will be ≥ k.
8+
The given num does not contain any leading zero.
9+
Example 1:
10+
11+
Input: num = "1432219", k = 3
12+
Output: "1219"
13+
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
14+
Example 2:
15+
16+
Input: num = "10200", k = 1
17+
Output: "200"
18+
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
19+
Example 3:
20+
21+
Input: num = "10", k = 2
22+
Output: "0"
23+
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
24+
25+
26+
27+
SOLUTION:
28+
29+
30+
31+
class Solution {
32+
public:
33+
string removeKdigits(string num, int k) {
34+
35+
int i;
36+
string s;
37+
38+
if(k==0)
39+
return num;
40+
41+
if(k>=num.length())
42+
{
43+
s="0";
44+
return s;
45+
}
46+
47+
for (const auto c : num) {
48+
while (k > 0 && !s.empty() && s.back() > c) {
49+
s.pop_back();
50+
k--;
51+
}
52+
s.push_back(c);
53+
}
54+
55+
56+
s.resize(s.length() - k);
57+
58+
for(i=0;i<s.length();i++)
59+
{
60+
if(s[i]!='0')
61+
{
62+
break;
63+
}
64+
}
65+
66+
s=s.substr(i,s.length()-i);
67+
68+
if(s.empty())
69+
s="0";
70+
71+
return s;
72+
}
73+
};

0 commit comments

Comments
 (0)