Skip to content

Instantly share code, notes, and snippets.

@lienista
Last active August 28, 2018 19:32
Show Gist options
  • Select an option

  • Save lienista/7f18bf49530648e21545c3188fb67006 to your computer and use it in GitHub Desktop.

Select an option

Save lienista/7f18bf49530648e21545c3188fb67006 to your computer and use it in GitHub Desktop.
(Algorithms in Javascript) Leetcode 258. Add Digits - Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
const sumDigits = (x) => {
if(x === '') {
return 0;
} else if(x < 10) {
return x;
} else {
let newX = x + '';
newX = newX.split('');
let sumX = parseInt(newX.pop()) + sumDigits(parseInt(newX.join('')));
return sumX < 10 ? sumX : sumX%10 + Math.floor(sumX/10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment