JS exercise to solve

Hello guys,

I have JS exerceise to solve. After trying a lot of times I would like to get a help,please.

Insert a number. Remove all zeros from the number, except the last one and print the number. If there are at most one zero, print “Nothing to remove”.

4050120 ---- 45120
7845012 ----- “Nothing to remove.”
0 ----- “Nothing to remove.”

Thanks in advance.

Below is what I have done till now.

var number = +prompt("Enter a number");
var sameNumber = number;
var numberOfZeros = 0, lastDigit = sameNumber % 10;

while (number !== 0) { // checking case of one 0
  if (number % 10 === 0) {
      numberOfZeros++;
  }
  number = Math.floor(number / 10);
}
if ((numberOfZeros === 1) || (sameNumber === 0)) {
  console.log("Nothing to remove");
} else {
    var currentDigit = sameNumber % 10;
    while (sameNumber !== 0) {
      if (currentDigit === 0) {
        
      }
      sameNumber = Math.floor(sameNumber / 10);
    }
}

You are overcomplicating matters. If the task is to remove random 0s, then just operate on a String.

function removeZeros(n) {
  return n.indexOf(0) === n.lastIndexOf(0) ? "Nothing to remove" : n.replace(/0(?!$)/g, "");
}

n argument must be a String. Do you specifically not want to work with a string?

Also[quote=“HovhannesMkoyan, post:1, topic:56626”]
Remove all zeros from the number, except the last one and print the number.
[/quote]
Does this mean except when zero is in the final position or except the last 0 regardless of position? If the latter, use /0(?![^0]*$)/g instead.

3 Likes

You beat me to it.

It seems that he needs to keep the last zero at any position, so your last regex is the correct one. :slight_smile:

7845012 ----- “Nothing to remove.”

Both when 0 is in the final position or in the middle and we have only one of it then we must keep it. okay thanks

function handleZero () {
	const x = parseInt(prompt('Type number'));
	const list = x.toString().split('');
	
	if(list.filter(el => el === '0').length < 2) {
		return console.log('Nothing to remove!');
		
	}
	return +list
		.filter((el, i, arr) => 
			el !== '0' || i === arr.lastIndexOf(el)
		).join('');
}

handleZero();

Does it suits your needs?

wow, I don’t think I can understand what you wrote here, it really is very complicated for me, as I don’t have that much knowledge of JS still. However thanks for helping :slight_smile: