Last active
August 28, 2018 19:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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