Previous Lecture Complete and continue  

  Sum the Digits

Difficulty Rating: 2.5 / 5


Code Solution

Review the solution below. Keep in mind, there are many different approaches to solve a problem. Don't focus on the solution, get a workable solution and improve it over time. As you continue solving problems your solutions and time it takes to problem solve will improve!


  function sumOfDigits(num){
    var sum = 0;
    var numStr = num.toString();
      
    for(var i = 0; i < numStr.length; i++){
      // or parseInt(numStr[i],10)
      sum += +numStr[i];
    }	
    return sum;
  }
  
Click the code snippet, use the embedded repl console above (dark blue), or your browser's console to run the code snippet above.