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

    Problem:

    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.

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

    Summary:

    给出一个整型数,反复求出它各个位数之和,直至和小于10。

    能否不使用循环和递归,复杂度为O(1)。

    Analysis:

    1、常规方法:

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

    2、Hint提示:Digital Root (https://en.wikipedia.org/wiki/Digital_root)

    Digital roots can be calculated with congruences in modular arithmetic rather than by adding up all the digits, a procedure that can save time in the case of very large numbers.

    It helps to see the digital root of a positive integer as the position it holds with respect to the largest multiple of 9 less than the number itself. For example, the digital root of 11 is 2, which means that 11 is the second number after 9. Likewise, the digital root of 2035 is 1, which means that 2035 − 1 is a multiple of 9. If a number produces a digital root of exactly 9, then the number is a multiple of 9.

       

    The formula is:

        or  

     1 class Solution {
     2 public:
     3     int addDigits(int num) {
     4         if (num <= 9) {
     5             return num;
     6         }
     7         else if (num % 9 == 0) {
     8             return 9;
     9         }
    10         else {
    11             return num % 9;
    12         }
    13     }
    14 };

    or

    1 class Solution {
    2 public:
    3     int addDigits(int num) {
    4         return 1 + ((num - 1) % 9);
    5     }
    6 };
  • 相关阅读:
    ISO9126 软件质量模型
    java 15.String
    java 14. ArrayList常用方法
    java 13. 方法重载构造方法块this用法
    linux ssh连接心跳检查断开连接
    关于递归,我有几句话想说
    pytest 报错 ImportError: cannot import name 'main'
    递归回溯剪枝之斐波那契数列
    appium-doctor诊断信息不完整
    数据驱动,关键字驱动,混合驱动简单模型
  • 原文地址:https://www.cnblogs.com/VickyWang/p/5988916.html
Copyright © 2011-2022 走看看