lo1gur
lo1gur

Reputation: 160

Variable doesn't seem to be taking on new value

  function reachOne(integer) {
      //deal with errors in input
      var array = [];
      //initialize multiply by putting it equal to 1
      var multiply = 1;
      var count = 0;

      if (integer < 0) {
          document.write('Do it again, Input should be a positive Integer')
      } else if (integer < 10 && integer >= 0) {
          document.write(count);
      } else {

          do {
              for (var i = 0; i < integer.length; i++) {
                  multiply = multiply * integer.charAt(i);
                  //if i try to write document.write(multiply), nothing appears
                  console.log("HELLO");
              }
              count++
          }

          while (multiply >= 10)



      }
      //if I write document.write(multiply) here, the result is 1 and not the product of all the numbers
  }
  reachSingle(254)        

    ----------

The code above should take a positive integer, and return the number of times the numbers inside that integer must be multiplied together to get one digit. Example: 254 would give 2: 2*5*4=40 and 4*0 = 0.

Upvotes: 1

Views: 33

Answers (2)

user5734311
user5734311

Reputation:

This should do it:

function reachOne(integer, count) {
	
  if (isNaN(integer) || integer < 1) return 0;
  
	var multiply = 1;
  if (isNaN(count)) count = 1;

  while (integer > 0) {    
    multiply = multiply * (integer % 10);
    integer = Math.floor(integer / 10);
  }
  if (multiply > 9) return reachOne(multiply, ++count);
  return count;
}

console.log(reachOne(254));

Upvotes: 1

Jonathan
Jonathan

Reputation: 2877

You need to first convert your variable to a string

var test = 254;
test = test.toString(); // you need to convert test to a string
var result = 1;
for (var x = 0; test.length > x; x++) {
    result *= test[x]; 
}

result is 40

Upvotes: 0

Related Questions