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

2.4 KiB

id title challengeType
5a23c84252665b21eecc803f Sum digits of an integer 5

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

Challenge Seed

function sumDigits (n) {
  // Good luck!
}

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
}