Skip to content

Instantly share code, notes, and snippets.

@zenHeart
Created June 9, 2018 04:08
Show Gist options
  • Save zenHeart/a301e44bc0f5e10e0a33d2754291d204 to your computer and use it in GitHub Desktop.
Save zenHeart/a301e44bc0f5e10e0a33d2754291d204 to your computer and use it in GitHub Desktop.
乘法持久性,persistence
exports.splitMultiply = splitMultiply;
exports.persistence = persistence;
/**
* 返回整数的乘法持久性.
For example:
because 3*9 = 27, 2*7 = 14, 1*4=4,and 4 has only one digit
persistence(39) === 3;
because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2
persistence(999) === 4;
because 4 is already a one-digit number
persistence(4) === 0;
* @param {Number} num 无符号正整形
*/
function persistence(num) {
let n = 0;
if(Number.isSafeInteger(num) && num > 0) {
while ((num+'').length > 1) {
num = splitMultiply(num);
n++
}
return n;
} else {
throw new Error('input must be positive safe integer');
}
}
/**
* 将整数拆分,按位相乘,例如 123,拆为 1*2*3,返回结果 6
* @param {Number} num 无符号整数
*/
function splitMultiply(num) {
let product = 1;
for (let i of num.toString()) {
product *= Number(i);
}
return product;
}
const {splitMultiply,persistence} = require('./persistence');
describe("persistence test",function() {
it("persistence",function() {
let testData = [
{
input:1,
expect:0,
},
{
input:34,
expect:2,
},
{
input:999,
expect:4,
}
]
testData.forEach((ele) => {
expect(persistence(ele.input)).toBe(ele.expect);
})
});
it("splitMultiply",function() {
let testData = [
{
input:1,
expect:1,
},
{
input:34,
expect:12,
},
{
input:999,
expect:729,
}
]
testData.forEach((ele) => {
expect(splitMultiply(ele.input)).toBe(ele.expect);
})
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment