[Leetcode] [JavaScript] ADD Digits

Source: Internet
Author: User

ADD Digits

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.

Follow up:
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 Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

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

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.