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


     

    Given a non-negative integernum, repeatedly add all its digits until the result has only one digit.

    For example:

    Givennum = 38, the process is like:3 + 8 = 11,1 + 1 = 2. Since2has only one digit, return it.

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

    题目让求各个数位的和,直到和小于10为止,

    方法一

    直观的想法就是直接相加,先想一下如何求各数位的和

    while(num != 0)
    {
        tmp += num % 10;
        num /= 10;
    }
     
    下面是完整代码
    class Solution {
        public int addDigits(int num) {
            
            
            while(num / 10 > 0)
            {   int sum = 0;   ////注意定义变量的位置
                while(num != 0)
                {
                    sum += num % 10;
                    num /= 10;
                }
                num = sum;
            }
            return num;
        }
    }
     

    方法二

    题目中说了不使用循环且时间复杂度为o(1),可以猜测必定有某种规律,题目是Add Digits,实际上这在数学上面被称为数根,先看下面例子:
    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
     
    这20个数的数根有循环,且循环周期为9,循环的计算公式为(n-1)% + 1,所以该题目i可以使用一行代码搞定
    class Solution {
    public:
        int addDigits(int num) {
            return (num - 1) % 9 + 1;  //周期第一位为1,若为2 则 + 2
        }
    };
  • 相关阅读:
    hdu 4474 转化为bfs + 一个巧妙的剪枝~
    数据结构几类排序的总结和完整代码 待续。。
    poj 2135 Farm Tour
    hdu 4374 (单调队列+dp)
    poj2391 Ombrophobic Bovines 拆点连边要注意
    hdu3507
    hdu1506
    poj2175
    poj3308
    poj3155 Hard Life
  • 原文地址:https://www.cnblogs.com/wxshi/p/7598402.html
Copyright © 2011-2022 走看看