O
O
OXPEHETb2019-10-26 01:37:30
JavaScript
OXPEHETb, 2019-10-26 01:37:30

How to add the digits of a number until you get a single value?

For example, there is a number 4654875646578.
What I want to implement:
4+6+5+4+8+7+5+6+4+6+5+7+8 = 75
The number is not single digit. it means
7 + 5 = 12
The number is not single, so
1+2 = 3
The number is single - we return 3.
I wrote the following logic:

function namerSummer(nn) {

  //перевожу в значение;
  nn = nn.toString();

  //создаю массив
  nn = nn.split('');

  //даю начальное значение
  var total = 0;

  //проверяю в массиве не одного значения?
  if (nn.length != 1) {

    //Если значение не одно запускаю цикл.
    for (var i = 0; i < nn.length; i++) {

      //Прибавляю предыдущую цифру
      total += nn[i] << 0;
    }

    //Запускаю функцию по новой, чтобы проверить сколько знаков в получившемся результате, и если что по новой складываю
    namerSummer(total);

  //Если в массиве одно значение
  } else if (nn.length == 1) {

    //Записываю в результат
    var total = nn.join('');
  }
  //Выводим результат
  return total;
}

In this case, the number 75 is displayed. What am I doing wrong? What is the logic error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaliy Pershin, 2019-10-26
@OXPEHETb

Because you are re- running namerSummer(total); but the data that you return from it you do not use. Should be something like this:
And it's not jQuery, it's regular js. I probably won’t explain in more detail, read about recursion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question