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

    给定一个整数,求每个数位上的数字之和,若结果大于10,则继续相加,直到其结果小于10.
    Input: 38
    Output: 2
    Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
      Since 2 has only one digit, return it.

    思路:
    一、递归,利用字符串辅助。

    int addDigits(int num) {
        string s;
        s = to_string(num);
        int res = 0;
        for (auto a : s) res += a - '0';
        return res < 10 ? res : addDigits(res);
    }


    二、题目说能不能不用循环或递归,在 O(1)时间复杂度得出结果。
    可以看到如下的范例:
    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
    ……..
    99 9
    100 1
    可以看到,以9为一个循环, x 非9的倍数时候,x%9就可以得到结果,但是x =9,18…这种的时候,x%9 = 0,单独判断即可。

    int addDigits(int num) {
        if (num == 0) return 0;
        if (num % 9 == 0) return 9;
        return num % 9;
    }

    Java 版:

    class Solution {
        public int addDigits(int num) {
            if( num < 10 ) return num;
            int sum = 0;
            while(num > 0){
                sum += num % 10 ;
                num /= 10;
            }
            return addDigits(sum);
        }
    }
  • 相关阅读:
    小结css2与css3的区别
    javascript变量的作用域
    javascript面向对象
    小结php中几种网页跳转
    foreach
    post与get,这两人到底神马区别??
    typescript遍历Map
    dataTable.js参数
    showModal()和show()的区别
    javascript中location.protocol、location.hostname和location.port
  • 原文地址:https://www.cnblogs.com/luo-c/p/12884889.html
Copyright © 2011-2022 走看看