[Leetcode] [JavaScript] ADD Digits

Source: Internet
Author: User

Given a non-negative integer num , repeatedly add all its digits until the result have only one digit.

For example:

Given num = 38 , the process is like: 3 + 8 = 11 , 1 + 1 = 2 . Since have only one 2 digit, return it.

Could do it without any loop/recursion in O (1) runtime?

Hint:

1. A naive implementation of the above process is trivial. Could come up with other methods?
2. What is all the possible results?
3. How does they occur, periodically or randomly?
4. You could find this Wikipedia article useful.

The maths problem is kneeling.

If you can use loops, the best case is to read the numbers, O (1) Time complexity.

Greedy, each read a number to do digit root operation, the final result is correct.

1 /**2 * @param {number} num3 * @return {number}4  */5 varAdddigits =function(num) {6     varstr = num.tostring (), res = 0, TMP1, TMP2;7      for(vari = 0; i < str.length; i++){8res = parseint (Str[i]) +Res;9         if(Res >= 10){TenTMP1 = parseint (RES/10); OneTMP2 = res% 10; Ares = TMP1 +TMP2; -         } -     } the     returnRes; -};

Best Answer Reference Wiki:https://en.wikipedia.org/wiki/digital_root

There are several ways to do this, and there are 2 of them listed here.

1  /*   2   * @param {number} num  3   * @return {number}  4  */ 5  var  adddigits = function   6  return  num = = 0? 0:num-9 * Math.floor ((num-1)/9 7 };
1 /* * 2 * @param {number} num 3 * @return {number} 4  */ 5 var function (num) {6     return 1 + (num-1)% 9; 7 };

[Leetcode] [JavaScript] ADD Digits

Related Keywords:
Related Article E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD