Posted By

Salamandern on 03/23/13


Tagged

math


Versions (?)

Last Edited at 03/23/13 09:50pm

Viewed 1 times

Summate() - Add the characters of a number


/ 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.

  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.