Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum up a number until it becomes 1 digit JS

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?

like image 654
VinceKaj Avatar asked Apr 18 '18 06:04

VinceKaj


People also ask

How do you sum digits in JavaScript?

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.

How do you reduce to single digit?

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.

How do you sum up a digit?

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 .

How do you get the first digit of a number JavaScript?

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.


1 Answers

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.

like image 114
Mark Avatar answered Sep 22 '22 03:09

Mark