```
var removeKdigits = function(num, k) {
let stack = [], numDigits = num.length;
for (let i = 0; i < numDigits; i++) {
while(k > 0 && stack.length && stack[stack.length - 1] > num[i]) {
stack.pop();
k--;
}
stack.push(num[i]);
}
stack = k > 0 ? stack.slice(0, -k) : stack;
return stack.join('').replace(/^0+/, '') || '0';
};
```