Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Build Lowest Number by Removing n digits from a given number
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// C++ program for the above approach

#include <bits/stdc++.h>
using namespace std;

string removeKdigits(string num, int k)
{
int n = num.size();
stack<char> mystack;
// Store the final string in stack
for (char c : num) {
while (!mystack.empty() && k > 0
&& mystack.top() > c) {
mystack.pop();
k -= 1;
}

if (!mystack.empty() || c != '0'){
mystack.push(c);
}
}

// Now remove the largest values from the top of the
// stack
while (!mystack.empty() && k--)
mystack.pop();
if (mystack.empty())
return "0";

// Now retrieve the number from stack into a string
// (reusing num)
while (!mystack.empty()) {
num[n - 1] = mystack.top();
mystack.pop();
n -= 1;
}
return num.substr(n);
}

int main()
{
string str = "765028321";
int k = 5;
cout << removeKdigits(str, k);
return 0;
}