iskaprekar
Version:
Is the integer a Kaprekar number
43 lines (38 loc) • 1.22 kB
JavaScript
function isKaprekar(num) {
if(num < 1) {
return false;
} else if(num === 1) {
return true;
}
// First we split the squared integer into an array of digits
var num2 = num * num;
var digits = splitNumber(num2);
// Then we split the array into two and combine the digits back into integers
for(var i = 0; i < digits.length; i++) {
if(digits.length > 1) {
var first = combineNumber(digits.slice(0, i));
var second = combineNumber(digits.slice(i));
} else {
var first = digits[0];
var second = 0;
}
// Then we compare if the sum of these integers is the value the function got called with
if((first + second) === num) {
return true;
}
}
return false;
}
function splitNumber(num) {
var res = ('' + num).split('').map(function(item) {
return parseInt(item, 10);
});
return res;
}
function combineNumber(arr) {
return parseInt(arr.join(''));
}
console.log(isKaprekar(2));
module.exports = isKaprekar;
module.exports.splitNumber = splitNumber;
module.exports.combineNumber = combineNumber;