zoukankan      html  css  js  c++  java
  • 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?

    给定一个非负整数num,反复添加的所有数字直到结果只有一个数字。

    num、结果、num%9

    0  0  0   

    1  1  1

    2  2  2

    ...

    9  9  0

    10  1  1

    11  2  2

    12  3  3

    13  4  4

    ...

    18  9  0

    19  1  1

    20  2  2

    ...

    99   9  0

    100  1  1

    ...

    999  9  0

    1000  1  1

    =>算法:

    public class Solution {
        public int AddDigits(int num)
        {
            return num == 0 ? 0 : num%9 == 0 ? 9 : num%9;
        }
    }

    看着比较乱,再优化一下:

    public class Solution {
        public int AddDigits(int num)
        {
            int[] result = {9, 1, 2, 3, 4, 5, 6, 7, 8};
    
            return num > 0 ? result[num%9] : 0;
        }
    }
  • 相关阅读:
    git取消文件跟踪
    servlet
    查杀端口进程
    初始化git仓库,并push到远端
    tomcat
    bootstrap
    idea中web工程错误
    i++和++i
    js算法
    编程工具
  • 原文地址:https://www.cnblogs.com/frank-zhang/p/5283678.html
Copyright © 2011-2022 走看看