[LeetCode][JavaScript]Add Digits

來源:互聯網
上載者:User

標籤:

Add Digits

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

For example:

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

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Hint:

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

 

 

 

 

數學題給跪了。

如果可以用迴圈,最好的情況是讀一遍數字,O(1)時間複雜度。

貪心,每讀一位元都做求Digit Root的操作,最後的結果是正確的。

 1 /** 2  * @param {number} num 3  * @return {number} 4  */ 5 var addDigits = function(num) { 6     var str = num.toString(), res = 0, tmp1, tmp2; 7     for(var i = 0; i < str.length; i++){ 8         res = parseInt(str[i]) + res; 9         if(res >= 10){10             tmp1 = parseInt(res / 10);11             tmp2 = res % 10;12             res = tmp1 + tmp2;13         }14     }15     return res;16 };

 

最佳答案參照wiki : https://en.wikipedia.org/wiki/Digital_root

好幾種寫法都可以,這裡列了2種。

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

 

 

 

 

[LeetCode][JavaScript]Add Digits

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.