2017-02-23 88 views
1
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)   

    ---------- 

上面的代码应该是一个正整数,并返回该整数内部的数字必须乘以一起得到一个数字的次数。例如:254会给2:2 * 5 * 4 = 40和4 * 0 = 0变量似乎没有承担新的价值

+0

你的'integer'参数看起来应该是一个数字,但'for'循环把它看作是一个字符串。因此'integer.length'将会是'undefined',所以'for'循环永远不会发生。 – Pointy

回答

0

您需要首先您的变量转换为字符串

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]; 
} 

结果是40

1

这应做到:

function reachOne(integer, count) { 
 
\t 
 
    if (isNaN(integer) || integer < 1) return 0; 
 
    
 
\t 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));