Skip to content

Instantly share code, notes, and snippets.

@alejandrolechuga
Created June 13, 2017 00:33
Show Gist options
  • Save alejandrolechuga/e3866567164530e3ded74bb3ff49c6b2 to your computer and use it in GitHub Desktop.
Save alejandrolechuga/e3866567164530e3ded74bb3ff49c6b2 to your computer and use it in GitHub Desktop.
// 123 => 6
// 199 => 19 -> 10 -> 1
// function numberToDigit(number) {
// var result = Array
// .from(number.toString())
// .reduce(function (acc, digit) {
// acc += parseInt(digit);
// return acc;
// }, 0);
// if (result > 9) {
// result = numberToDigit(result);
// }
// return result;
// }
function numberToDigit(number) {
var acc = 0;
while(number > 0) {
var digit = number % 10;
acc += digit;
number = (number - digit) / 10;
}
if (acc > 9) {
acc = numberToDigit(acc);
}
return acc;
}
console.log(numberToDigit(123));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment