Before you mark duplicate note that it isn't. Others didn't look for the exact same thing as me.
What is the most compact possible way to sum up a number in javascript until there is only one digit left. For example: You input 5678 then the script adds it together (5+6+7+8) and gets 26, but since its more than 1 digit it adds it again and gets 2+6=8.
Is there anyway to do this with a number of any size? And how compact can the script get?
If you treat the number as a string ('2568'), then split the string on every character (str. split('')), you will have every digit listed out separately in an array. Each digit is still a string, but you can then cast each to a number and add them up.
Given a number N, the task is to reduce it to a single-digit number by repeatedly subtracting the adjacent digits. That is, in the first iteration, subtract all the adjacent digits to generate a new number, if this number contains more than one digit, repeat the same process until it becomes a single-digit number.
We can obtain the sum of digits by adding the digits of a number by ignoring the place values. So, for example, if we have the number 567 , we can calculate the digit sum as 5 + 6 + 7 , which will give us 18 .
To get the first digit of a number:Access the string at index 0 , using square brackets notation e.g. String(num)[0] . Convert the result back to a number to get the first digit of the number.
If you're looking for short, it's hard to beat:
var n = 5678;
sum = n % 9 || 9;
console.log(sum)
If you're curious about how that works, see: casting out nines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With