sum of the digits of a number javascript

后端 未结 4 832
无人及你
无人及你 2021-01-04 13:07

I saw a bunch of other posts on this topic but none in javascript. here is my code.

var theNumber = function digitAdd (base, exponent) {
    var number = 1;
         


        
相关标签:
4条回答
  • 2021-01-04 13:36

    The second function uses the modulo operator to extract the last digit:

      1236 % 10
    = 1236 - 10 * floor(1236 / 10)
    = 1236 - 1230
    = 6
    

    When the last digit is extracted, it is subtracted from the number:

      1236 - 6
    = 1230
    

    And the number is divided by 10:

      1230 / 10
    = 123
    

    Each time this loop repeats, the last digit is chopped off and added to the sum.

    The modulo operator returns the single digit if the left hand side is smaller than the right (which will happen for any 1-digit number), which is when the loop breaks:

      1 % 10
    = 1
    

    This is how the leading digit gets added to the total.


    A less numeric alternative would be this:

    function sumDigits(number) {
      var str = number.toString();
      var sum = 0;
    
      for (var i = 0; i < str.length; i++) {
        sum += parseInt(str.charAt(i), 10);
      }
    
      return sum;
    }
    

    It does literally what you are trying to do, which is iterate over the digits of the number (by converting it to a string).

    0 讨论(0)
  • 2021-01-04 13:44

    i use it :)

    var result = eval('123456'.replace(/(\d)(?=\d)/g, '$1+'));
    alert(result); // 21

    without eval

    var result = '123456'.split('').reduce(function(a,b){ return +a+ +b; });
    alert(result); // 21

    0 讨论(0)
  • 2021-01-04 13:51

    Not sure what you meant, In case you were asking about while loop..

    The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:

    while (expression) {
         statement(s)
    }
    

    The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

    The while loop here is extracting digits one by one from the actual number and adding those. Try to do each step manually and you will get it.

    0 讨论(0)
  • 2021-01-04 14:01

    i use this :

    '123456'.split('').map(function(e){return parseInt(e)}).reduce(function(a,b){return a+b}); //21
    

    Update (ES6 syntax) :

    [...'123456'].map(e=>parseInt(e)).reduce((a,b)=>a+b); //21
    
    0 讨论(0)
提交回复
热议问题