Summate() - Add the characters of a number


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. function summate(n){
  2.  
  3. var chars = new Array();
  4. var c;
  5. var l = "" + n + "";
  6. var ans = 0;
  7. l = l.length;
  8.  
  9. for(var i = 0;i < l;i++){
  10.  
  11. c = n;
  12. for(var j = 0;j<i;j++){
  13.  
  14. c -= chars[j]*Math.pow(10,(l-1)-j);
  15. }
  16.  
  17. c /= Math.pow(10,(l-1)-i);
  18. c = Math.floor(c);
  19. chars.push(c);
  20. }
  21. while(l>0){
  22.  
  23. ans += chars[l-1];
  24. l--;
  25. }
  26. return ans;
  27. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.