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

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

    Example:

    Input: 38
    Output: 2 
    Explanation: 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?

    题意是给一个整数,求每一位上的数的加和。

    两种做法,第一种是用递归,比较直观。对数字取余得到最低位的数字,然后再做加法直到num === 0。

    JavaScript实现

     1 /**
     2  * @param {number} num
     3  * @return {number}
     4  */
     5 var addDigits = function(num) {
     6     let res = 0;
     7     while (num != 0) {
     8         res += num % 10;
     9         num = parseInt(num / 10);
    10     }
    11     if (res >= 10) {
    12         return addDigits(res);
    13     } else {
    14         return res;
    15     }
    16 };

    Java实现

     1 class Solution {
     2     public int addDigits(int num) {
     3         int res = 0;
     4         while (num != 0) {
     5             res += num % 10;
     6             num /= 10;
     7         }
     8         if (res >= 10) {
     9             return addDigits(res);
    10         } else {
    11             return res;
    12         }
    13     }
    14 }

    第二种是看到了每次加和的规律,具体解释参见grandyang大神的第二个解法,https://www.cnblogs.com/grandyang/p/4741028.html

    JavaScript实现

    1 /**
    2  * @param {number} num
    3  * @return {number}
    4  */
    5 var addDigits = function(num) {
    6     return ((num - 1) % 9) + 1;
    7 };

    Java实现

    1 class Solution {
    2     public int addDigits(int num) {
    3         return (num - 1) % 9 + 1;
    4     }
    5 }

    LeetCode 题目总结

  • 相关阅读:
    20210524
    20210521
    20210520
    20210519
    20210518
    20210517
    字符设备驱动三
    字符设备驱动二
    字符设备驱动一
    git基本操作
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11695972.html
Copyright © 2011-2022 走看看