zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Add Digits

    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 = 111 + 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.

    数学题给跪了。

    如果可以用循环,最好的情况是只读一遍。

    贪心,每读一数都做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} num
    3  * @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} num
    3  * @return {number}
    4  */
    5 var addDigits = function(num) {
    6     return 1 + (num - 1) % 9;
    7 };
  • 相关阅读:
    移动端图片按比例裁剪
    bootstrap悬停下拉菜单显示
    videojs兼容ie8
    ie浏览器不支持多行隐藏显示省略号
    rem和px
    浏览器默认返回,页面刷新
    centos src compile gcc 7.3
    docker与gosu
    centos 安装 kernel
    docker proxy
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4735356.html
Copyright © 2011-2022 走看看