Is there a method for folding numbers?
For example:
15 = 1 + 5 = 6 or
584 = 5 + 8 + 4 = 17 You can take the balances and round off:
function digsum(n) { var sum = 0; while(n) sum += n % 10, n = Math.floor(n / 10); return sum; } digsum(15) // 6 digsum(584) // 17 function sum(a) { return a.toString().split('').reduce(function(a, b) { return a + parseInt(b); }, 0); } console.log(sum(584)) ES2015
function sum(a) { return a.toString().split('').reduce((a, b) => a + parseInt(b), 0); } console.log(sum(584)) split - splits a string into an array of strings, reduce - applies a function to each value of the array, from left to right, reducing it to a single value. And so +1 :) - Denis Bubnov+b instead of parseInt(b) . But this is more than "number of characters" vs "ease of understanding of the code." - Regentit seems like there is no ready method, you can write it yourself, break the string into characters and put them together
function sum(number) { var digits, sum = 0; if(Object.prototype.toString.call(number) == '[object Array]') { // из комментов - либо (number instanceof Array) digits = number; } else { digits = number.toString().split('') } for(var i = 0; i < digits.length; i++) { sum += parseInt(digits[i]); } return sum; } а если у нас массив? - you do not know what cycles are and how to calculate the sum of all numbers using it? maybe then you read a little book on bases of language? - Alexey ShimanskyThere is no such method.
function digits_sum(number){ let result = 0; for(let i = 1; i<number; i=i*10) result += ((number-number%i)/i)%10; return result; } console.log(digits_sum(1234)); console.log(digits_sum(88)); console.log(digits_sum(5555555555)); 1 , 10 , 100 , etc. Must be i <= number . As for i = i * 10 instead of i *= 10 and saving on spaces, this is already a subjective matter. - RegentSource: https://ru.stackoverflow.com/questions/681791/
All Articles
-1? The person asked the correct question, what is a simple question does not mean to ask? - Raz Galstyan