乘以数字的每个元素,直到长度为1

发布于 2025-02-08 18:02:58 字数 292 浏览 1 评论 0原文

如何将数字的每个元素乘以数字只有一个数字?

function persistence(number) {
  let a = number.toString();
  let b = 1;

  for (const ch of a) {
    b *= +ch
  }

  console.log(b) // 27
} 
// persistence(39)
// 39 --> 4 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)

How to multiply every element of a number until number has one digit only?

function persistence(number) {
  let a = number.toString();
  let b = 1;

  for (const ch of a) {
    b *= +ch
  }

  console.log(b) // 27
} 
// persistence(39)
// 39 --> 4 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃兔兔 2025-02-15 18:02:58

您可以使用递归调用persistence()函数,直到结果具有length == 1

const result = persistence(47);
//--> returns 6 because: 4*7=28 => 2*8=16 => 1*6=6
console.log(result);

function persistence(num) {
  
  let a = num.toString();
  let b = 1;

  for (const ch of a) {
    b *= parseInt(ch);
  }    
  
  if (b.toString().length > 1)
    return persistence(b);  
    
  return b;
}

You could call the persistence() function with recursion until the result has length == 1

const result = persistence(47);
//--> returns 6 because: 4*7=28 => 2*8=16 => 1*6=6
console.log(result);

function persistence(num) {
  
  let a = num.toString();
  let b = 1;

  for (const ch of a) {
    b *= parseInt(ch);
  }    
  
  if (b.toString().length > 1)
    return persistence(b);  
    
  return b;
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文