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

    非负整数各位相加,直到剩下最后一位。

    简单的思路如下:

    假设我们有一个函数sum(a)

    这个函数可以处理a的每一位相加那么实现如下

    if(sum(a)>9) return sum(sum(a))

    else return sum(a)

    但是现在的要求是时间复杂度为o(1)

    先上代码

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

    思路如下,首先返回值一定是0-9。那么考虑简单情况,例如一个3位数abc,原值为t1=(100a+10b+c) 经过一步各位累加的值为t2=(a+b+c),如果t2<9那么就是t2,而t1-t2一定能被9整除,所以返回值即t1除以9的余数

    那么考虑特殊情况,整除返回应该是9而不是0,0返回是0.即可得到答案 

  • 相关阅读:
    C# 对XML操作-实例
    XML
    得到一个随机数组的方法
    Node Redis 小试
    Hexo快速搭建静态博客并实现远程VPS自动部署
    substr.js 字符串切割
    GraphicsMagick 学习笔记
    store.js 跨浏览器的localStorage
    bodyParser中间件的研究
    Sublime Text 使用指南
  • 原文地址:https://www.cnblogs.com/icysnow/p/5868840.html
Copyright © 2011-2022 走看看