/ Published in: JavaScript
This function will return the sum of the characters making up a number. For example, summate(321) will return 6. summate(123) will also return 6, because both 123 and 321 are made out of the same characters. Supports integers of any length, but only positive ones. Negatives get weird. Non-integers get rounded.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function summate(n){ var chars = new Array(); var c; var l = "" + n + ""; var ans = 0; l = l.length; for(var i = 0;i < l;i++){ c = n; for(var j = 0;j<i;j++){ c -= chars[j]*Math.pow(10,(l-1)-j); } c /= Math.pow(10,(l-1)-i); c = Math.floor(c); chars.push(c); } while(l>0){ ans += chars[l-1]; l--; } return ans; }