freeCodeCamp/curriculum/challenges/english/10-coding-interview-prep/rosetta-code/sum-digits-of-an-integer.md

1.9 KiB

id title challengeType forumTopicId
5a23c84252665b21eecc803f Sum digits of an integer 5 302331

Description

Write a function that takes a string as a parameter. This string represents a number that can be in any base (less than 37) and return the sum of its digits.
  • 110 sums to 1
  • 123410 sums to 10
  • fe16 sums to 29
  • f0e16 sums to 29

Instructions

Tests

tests:
  - text: <code>sumDigits</code> should be a function.
    testString: assert(typeof sumDigits == 'function');
  - text: <code>sumDigits("1")</code> should return a number.
    testString: assert(typeof sumDigits("1") == 'number');
  - text: <code>sumDigits("1")</code> should return <code>1</code>.
    testString: assert.equal(sumDigits("1"), 1);
  - text: <code>sumDigits("12345")</code> should return <code>15</code>.
    testString: assert.equal(sumDigits("12345"), 15);
  - text: <code>sumDigits("254")</code> should return <code>11</code>.
    testString: assert.equal(sumDigits("254"), 11);
  - text: <code>sumDigits("fe")</code> should return <code>29</code>.
    testString: assert.equal(sumDigits("fe"), 29);
  - text: <code>sumDigits("f0e")</code> should return <code>29</code>.
    testString: assert.equal(sumDigits("f0e"), 29);
  - text: <code>sumDigits("999ABCXYZ")</code> should return <code>162</code>.
    testString: assert.equal(sumDigits("999ABCXYZ"), 162);

Challenge Seed

function sumDigits(n) {

}

Solution

function sumDigits(n) {
  n += '';
  for (var s = 0, i = 0, e = n.length; i < e; i += 1)
    s += parseInt(n.charAt(i), 36);
  return s;
}