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;
        }
    }
  • 相关阅读:
    Exp8-Web综合
    Exp7-网络欺诈防范
    Exp6-MSF应用基础
    加密API学习
    Exp5 信息搜集与漏洞扫描
    Exp4-恶意代码分析
    Exp3-免杀原理
    Exp2-后门原理与实践
    leetcode 22括号生成 暴力法
    413 等差数列划分
  • 原文地址:https://www.cnblogs.com/frank-zhang/p/5283678.html
Copyright © 2011-2022 走看看