Skip to content

Instantly share code, notes, and snippets.

@joshkautz
Created September 4, 2016 14:35
Show Gist options
  • Save joshkautz/c88031bd46681f77b9cb3e51d25a2d9c to your computer and use it in GitHub Desktop.
Save joshkautz/c88031bd46681f77b9cb3e51d25a2d9c to your computer and use it in GitHub Desktop.
CodeFights - JavaScript code to calculate the sum of all digits in an integer
function digitSum(n) {
var sum = 0;
var string = n.toString();
for(i=0; i < string.length; i++){
sum = sum + parseInt(string.substring(i, i+1));
}
return sum;
}
@Slackluky
Copy link

You can also just return n%9. I know its not as interesting. But its faster and smaller.

sorry but, if your n = 28, the output will be 1 ( 28%9 = 1 ) instead of 10

@mathiasrw
Copy link

You are right. Sorry about that. The n%9 is only if you want to keep adding the digits until you have only one digit left.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment