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.

    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?


    题目标签:Math

      如果要满足O(1) 的要求,这里需要用到digital root 公式。

      首先来看一下规律:

      1   - 1

      2   - 2

      3   - 3

      4   - 4 

      5   - 5

      6   - 6

      7   - 7

      8   - 8

      9   - 9 *

      10 - 1

      11 - 2

      12 - 3 

      13 - 4

      14 - 5

      15 - 6

      16 - 7

      17 - 8

      18 - 9 *

      19 - 1

      20 - 2

      ...

      我们可以发现 digital root 永远是 1 到 9 循环,所以我们可以利用 % 9。

      Step 1: 如果num 是0,那么返回 0;

      Step 2: 如果num 可以被 9 整除,那么返回 9;

      Step 3: 剩下的情况,只要返回 num % 9。

    Java Solution:

    Runtime beats 26.24% 

    完成日期:06/16/2017

    关键词:Digital root

    关键点:digital root 从1 到 9 循环 -> 利用 % 9 得到 digital root

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

    参考资料:http://www.cnblogs.com/grandyang/p/4741028.html

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    SpringBoot自定义starter
    Vue中$nextTick()用法
    Vue中filters使用data的数据
    Vue页面生成二维码
    Vue页面实现打印功能
    Vue中监听(watch)的使用
    Vue中判断对象属性是否存在
    大三寒假学习进度(十九)
    大三寒假学习进度(十八)
    大三寒假学习进度(十七)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8390436.html
Copyright © 2011-2022 走看看