6kyu Persistent Bugger

题目:

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

编写一个函数,持久性,它接受一个正参数num并返回它的乘法持久性,这就是你必须将数字中的数字乘上数字直到你到达一个数字的次数。

For example:

persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit

persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2

persistence(4) === 0 // because 4 is already a one-digit number

 Sample Tests:

describe('Initial Tests', function () {
  Test.assertEquals(persistence(39),3);
  Test.assertEquals(persistence(4),0);
  Test.assertEquals(persistence(25),2);
  Test.assertEquals(persistence(999),4);
});

 

答案: 

    // 1

              function persistence(num) {

                     var times = 0;

                     num = num.toString();

                     while (num.length > 1) {

                            times++;

                            num = num.split('').map(Number).reduce((a, b) => a * b).toString();

                     }

                     return times;

              }

 

              // 2

              const persistence = num => {

                     return `${num}`.length > 1 ? 1 + persistence(`${num}`.split('').reduce((a, b) => a * +b)) : 0;

                     // +b 隐式类型转换 字符串转数字 +前为空自动默认为求和运算而不是字符串拼接

                     // * - / % 都可以隐式类型转换 字符串转数字

                     // 此处并不需要+  a和b都是字符串 a*b 隐式转换为数字

              }

 

              // 3

              function persistence(num) {

                     var i = 0;

                     for (i; num.toString().length > 1; i++) {

                            num = num.toString().split('').reduce()(function(x,y){return x * y});

                     }

                     return i;

              }

 

              // 4

              const prod = (n) => (n + '').split('').reduce((p,v) => p * v, 1)

              function persistence(num) {

                     let p = 0;

                     while (num > 9) {

                            num = prod (num);

                            p++;

                     }

                     return p;

              }

转载于:https://www.cnblogs.com/tong24/p/7306247.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值