简体   繁体   English

7的可除性规则-Codewars Javascript挑战

[英]A Rule of Divisibility by 7 - Codewars Javascript Challenge

For this codewars challenge 对于这个Codewar挑战

The following code passes tests but it's experiencing a timeout error: 以下代码通过了测试,但是遇到超时错误:

 function seven(m) { let count = 0; m = String(m); while (Number(m.slice(0, m.length - 1)) - (Number(m[m.length - 1]) * 2) % 7 !== 0) { let first = Number(m.slice(0, m.length - 1)); let second = Number(m[m.length - 1]) * 2; m = first - second; count++; m = String(m); } return [Number(m), count]; } console.log(seven(483)); 

As I understand, the idea is to continue breaking a number down until it's divisible by 7. Stop when the number has at most 2 digits. 据我了解,这个想法是继续分解一个数字,直到被7整除为止。当该数字最多为 2位时停止。

A number m of the form 10x + y is divisible by 7 if and only if x − 2y is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. 当且仅当x-2y可被7整除时,形式为10x + y的数字m可被7整除。换句话说,从剩余数字形成的数字中减去最后一位的两倍。 Continue to do this until a number known to be divisible or not by 7 is obtained; 继续执行此操作,直到获得一个已知的可被7整除或不可除的数; you can stop when this number has at most 2 digits because you are supposed to know if a number of at most 2 digits is divisible by 7 or not. 您可以在此数字最多2位时停止,因为您应该知道最多2位数字是否可以被7整除。

The original number is divisible by 7 if and only if the last number obtained using this procedure is divisible by 7. 当且仅当使用此过程获得的最后一个数字可被7整除时,原始数字才可被7整除。

Example : 范例

1 - m = 371 -> 37 − (2×1) -> 37 − 2 = 35 ;

thus, since 35 is divisible by 7, 371 is divisible by 7. 因此,由于35可被7整除,因此371可被7整除。

And I'm not sure how else to optimize this code. 而且我不确定如何进一步优化此代码。 Perhaps I'm misunderstanding the question and that's why my while-loop is overly complicated. 也许我对这个问题有误解,这就是为什么while循环过于复杂。 Any suggestions? 有什么建议么?

EDIT - second attempt - trying to avoid converting to String and back to Number: 编辑 -第二次尝试-尝试避免转换为String并返回Number:

 function seven (m) { let count = 0; while ((String(m).length > 2) && (m % 7 !== 0)) { let last = (m % 10); let first = (m - last) / 10; m = (first - (last * 2)); count++; } return [m, count]; } 

This is passing 84 tests, failing 26. 这通过了84次测试,未通过26次。

You can just compute the input until it is smaller than 3 digits and return the count. 您可以只计算input直到input小于3位,然后返回计数。

Please try this: 请尝试以下方法:

function seven(m) {    
  let count = 0;

  while(m > 99) {
    m = parseInt(m / 10) - (2 * (m % 10)); 
    count++;
  }

  return [m, count];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM